Lecture #8. Javascript DOM. Async
Lecture #8. Javascript DOM. Async
Лабораторна робота №1
Лабораторна робота №2
2
DOM Mode
The DOM is the Document Object Model of a page. It is the code of the structure of
a webpage. JavaScript comes with a lot of different ways to create and manipulate
HTML nodes.
Node Properties
attributes — Returns a live collection of all attributes registered to an element
baseURI — Provides the absolute base URL of an HTML element
childNodes — Gives a collection of an element’s child nodes Tutorial is
firstChild — Returns the first child node of an element here
lastChild — The last child node of an element
nextSibling — Gives you the next node at the same node tree level
nodeName —Returns the name of a node https://github.com/Aroxed/js-todo-mvc
nodeType — Returns the type of a node
nodeValue — Sets or returns the value of a node
ownerDocument — The top-level document object for this node
parentNode — Returns the parent node of an element
previousSibling — Returns the node immediately preceding the current one 3
Node Methods
appendChild() — Adds a new child node to an element as the last child node
cloneNode() — Clones an HTML element
hasAttributes() — Returns true if an element has any attributes, otherwise false
hasChildNodes() — Returns true if an element has any child nodes, otherwise false
insertBefore() — Inserts a new child node before a specified, existing child node
isEqualNode() — Checks if two elements are equal
isSameNode() — Checks if two elements are the same node
removeChild() — Removes a child node from an element
replaceChild() — Replaces a child node in an element
4
Element Methods
getAttribute() — Returns the specified attribute value of an element node
getElementsByTagName() — Provides a collection of all child elements with the
specified tag name
hasAttribute() — Returns true if an element has any attributes, otherwise false
removeAttribute() — Removes a specified attribute from an element
setAttribute() — Sets or changes the specified attribute to a specified value
setAttributeNode() — Sets or changes the specified attribute node
setAttributeNodeNS() — Adds a new namespaced attribute node to an element
5
Elements Search Methods
document.querySelectorAll("p.warning,
Element.querySelector() p.note");
Element.querySelectorAll()
Document.querySelector() var el = document.querySelector("#main,
Document.querySelectorAll() #basic, #exclamation");
6
Working with the User Browser
Window Properties
document — Returns the document object for the window
frames — Returns all <iframe> elements in the current window
history — Provides the History object for the window
innerHeight — The inner height of a window’s content area
innerWidth — The inner width of the content area
location — Returns the location object for the window
navigator — Returns the Navigator object for the window
opener — Returns a reference to the window that created the window
outerHeight — The outer height of a window, including toolbars/scrollbars
outerWidth — The outer width of a window, including toolbars/scrollbars
pageXOffset — Number of pixels the current document has been scrolled
horizontally
pageYOffset — Number of pixels the document has been scrolled vertically
parent — The parent window of the current window
screen — Returns the Screen object for the window
7
self — Returns the current window
Working with the User Browser
Window Methods
alert() — Displays an alert box with a message and an OK button
clearInterval() — Clears a timer set with setInterval()
clearTimeout() — Clears a timer set with setTimeout()
close() — Closes the current window
confirm() — Displays a dialogue box with a message and an OK and Cancel button
focus() — Sets focus to the current window
open() — Opens a new browser window
print() — Prints the content of the current window
prompt() — Displays a dialogue box that prompts the visitor for input
resizeTo() — Resizes the window to a specified width and height
scrollTo() — Scrolls the document to specified coordinates
setInterval() — Calls a function or evaluates an expression at specified intervals
setTimeout() — Calls a function or evaluates an expression after a specified
interval
8
JavaScript Events
Mouse
onclick — The event occurs when the user clicks on an element
oncontextmenu — User right-clicks on an element to open a context menu
ondblclick — The user double-clicks on an element
onmousedown — User presses a mouse button over an element
onmouseenter — The pointer moves onto an element
onmouseleave — Pointer moves out of an element
onmousemove — The pointer is moving while it is over an element
onmouseover — When the pointer is moved onto an element or one of its children
onmouseout — User moves the mouse pointer out of an element or one of its
children
onmouseup — The user releases a mouse button while over an element
9
JavaScript Events
Keyboard
onkeydown — When the user is pressing a key down
onkeypress — The moment the user starts pressing a key
onkeyup — The user releases a key
Frame/Window
onabort — The loading of a media is aborted
onbeforeunload — Event occurs before the document is about to be unloaded
onerror — An error occurs while loading an external file
onhashchange — There have been changes to the anchor part of a URL
onload — When an object has loaded
onpagehide — The user navigates away from a webpage
onpageshow — When the user navigates to a webpage
onresize — The document view is resized
onscroll — An element’s scrollbar is being scrolled
onunload — Event occurs when a page has unloaded 10
JavaScript Events
Form
onblur — When an element loses focus
onchange — The content of a form element changes (for <input>, <select> and
<textarea>)
onfocus — An element gets focus
onfocusin — When an element is about to get focus
onfocusout — The element is about to lose focus
oninput — User input on an element
oninvalid — An element is invalid
onreset — A form is reset
onsearch — The user writes something in a search field (for <input="search">)
onselect — The user selects some text (for <input> and <textarea>)
onsubmit — A form is submitted
11
JavaScript Events
Drag
ondrag — An element is dragged
ondragend — The user has finished dragging the element
ondragenter — The dragged element enters a drop target
ondragleave — A dragged element leaves the drop target
ondragover — The dragged element is on top of the drop target
ondragstart — User starts to drag an element
ondrop — Dragged element is dropped on the drop target
Clipboard
oncopy — User copies the content of an element
oncut — The user cuts an element’s content
onpaste — A user pastes the content in an element
12
Errors
When working with JavaScript, different errors can occur. There are several ways of
handling them:
try — Lets you define a block of code to test for errors
catch — Set up a block of code to execute in case of an error
throw — Create custom error messages instead of the standard JavaScript errors
finally — Lets you execute code, after try and catch, regardless of the result
13
Private scope
// Anonymous self-invoking function
(function () {
// private scope here here
})()
// Module pattern
var Module = (function () {
function privateFn() {
// do something
}
return {
publicFn() {
console.log('public')
}
}
})()
Module.publicFn() // 'public'
Module.privateFn() // Uncaught ReferenceError: privateFn is not
defined 14
HTML DOM Closure Example
<body>
<button class="btn">Click 2 times</button>
<button class="btn">Click 3 times</button>
<script>
var buttons = document.querySelectorAll(".btn")
for (var index=0; index<buttons.length; index++) {
buttons[index].addEventListener("click", (function(max_count) {
// init the count to 0
var count = 0; // ACCESSIBLE IN THE INNER FUNCTION
var max_count = max_count; // ACCESSIBLE IN THE INNER FUNCTION
return function(e) {
count++;
if (count === max_count) {
// do something every third time
alert(max_count + " times clicked");
//reset counter
count = 0;
}
};
})(index + 2));
}
</script>
</body> 15
.apply() and .call()
Remember: context === this
They both to pretty much the same thing: allows you to change the context while
calling a function. The difference between them are simple:
When using .call() the arguments should be comma separated (like any
regular function) and .apply() expects an Array of arguments;
function contextValue() {
console.log(`this value: ${this}`)
}
contextValue() // this value: [object Window]
contextValue.call(window) // this value: [object Window]
contextValue.apply(document) // this value: [object HTMLDocument]
contextValue.call('a string') // this value: a string
16
.bind()
It was introduced on ECMAScript5 and it’s used to bind the value of context and
other arguments before calling the function.
function contextValue() {
console.log(`this value: ${this}`)
}
contextValue.bind(document) // does nothing, no error
const documentContext = contextValue.bind(document)
documentContext() // this value: [object HTMLDocument]
contextValue.bind(document)() // this value: [object HTMLDocument]
17
Underscore examples (Once and
Throttle)
// _.once(func)
// Creates a version of the function that can only be called one
time
// (with any arguments). Repeated calls to the modified function
// will have no effect, returning the value from the original call.
// Useful for initialization functions, instead of having to set
// a boolean flag and then check it later.
—
// _.throttle(function, wait)
// Returns a new, throttled version of the passed function that,
// when invoked repeatedly (with any arguments), calls the original
function
// at most once every wait milliseconds, and otherwise just returns
// the last computed result. Useful for rate-limiting events
Javascript by example - a Javascript
Custom events handbook
We can not only assign handlers, but also generate events from JavaScript.
Events can be created with the Event constructor as follows:
const event = new Event('build');
// Listen for the event.
elem.addEventListener('build', function (e) { /* ... */ }, false);
// Dispatch the event.
elem.dispatchEvent(event);
19
Classes
class Circle extends Shape {
Calling superclass methods
Constructor
expand (n) {
constructor (radius) {
return super.expand(n) * Math.PI
this.radius = radius
}
}
Static methods
Methods
static createFromDiameter(diameter) {
getArea () {
return new Circle(diameter / 2)
return Math.PI * 2 * this.radius
}
}
}
Object.values(person)
// [21, "John"]
Object.entries(person)
// [["age", 21], ["name", "John"]]
Modules
Imports Exports
import 'helpers' export default function () { ··· }
// aka: require('···') // aka: module.exports.default = ···
import Express from 'express' export function mymethod () { ··· }
// aka: const Express = require('···').default || // aka: module.exports.mymethod = ···
require('···') export const pi = 3.14159
import { indent } from 'helpers' // aka: module.exports.pi = ···
// aka: const indent = require('···').indent
import * as Helpers from 'helpers'
// aka: const Helpers = require('···')
import { indentSpaces as indent } from
'helpers'
// aka: const indent = require('···').indentSpaces
Generators
function* idMaker () {
For..of iteration
let id = 0
for (let i of iterable) {
while (true) { yield id++ }
···
}
}
let gen = idMaker()
For iterating through generators and
gen.next().value // → 0
arrays.
gen.next().value // → 1
gen.next().value // → 2
// creating objects
const person1 = new Person();
const person2 = new Person();
36
JavaScript Prototype property
In JavaScript, every function and object has a property named prototype by
default. For example,
function Person () {
this.name = 'John',
this.age = 23
}
Person.prototype.greet = function() {
console.log('hello' + ' ' + this.name);
}
person.greet() // hello John
-------
String.prototype.reverse = function () {
let result = "";
for (let i=0;i<this.length; i++)
result = this[i] + result;
return result;
}
let s = ‘abcd’;
s.reverse(); // ‘dcba’
38
Changing Prototype
If a prototype value is changed, then all the new objects will have the
changed property value. All the previously created objects will have the
previous value.
// constructor function
function Person() {
this.name = 'John'
} // changing the property value of prototype
Person.prototype = { age: 50 }
// add a property
Person.prototype.age = 20; // creating new object
const person3 = new Person();
// creating an object
const person1 = new Person(); console.log(person3.age); // 50
console.log(person1.age); // 20
console.log(person1.age); // 20
39
JavaScript Prototype Chaining
If an object tries to access the same property that is in the constructor function
and the prototype object, the object takes the property from the constructor
function. For example,
function Person() {
this.name = 'John'
}
// adding property
Person.prototype.name = 'Peter';
Person.prototype.age = 23
// callback function
// executed only after the greet() is executed
myFunction(name);
}
// callback function
function sayName(name) {
console.log('Hello' + ' ' + name);
}
42
Create a Promise
If the promise returns successfully, the resolve() function is called. And, if an error
occurs, the reject() function is called.
43
Promise
44
JavaScript Promise Chaining
Promises are useful when you have to handle more than one asynchronous task,
one after another. For that, we use promise chaining.
You can perform an operation after a promise is resolved using methods then(),
catch() and finally().
45
Chaining the Promise with then()
let countValue = new Promise(function (resolve, reject) {
resolve('Promise resolved'); });
// executes when promise is resolved successfully
countValue.then(
function successValue(result) {
console.log(result);
},
)
.then(
function successValue1() {
console.log('You can call multiple functions this way.');
},
);
46
JavaScript catch() method
The catch() method is used with the callback when the promise is rejected or if an
error occurs. For example,
// returns a promise
let countValue = new Promise(function (resolve, reject) {
reject('Promise rejected');
});
// executes when promise is resolved successfully
countValue.then(
function successValue(result) {
console.log(result);
},
)
// executes if there is an error
.catch(
function errorValue(result) {
console.log(result);
}
);
47
JavaScript Promise vs Callbacks
api(function(result){
api().then(function(result) { api2(function(result2){
return api2() ; api3(function(result3){
}).then(function(result2) { // do work
return api3(); if(error) {
}).then(function(result3) { // do something
// do work }
}).catch(function(error) { else {
//handle any error that may occur before this // do something
point }); }
});
});
});
48
JavaScript Promise Methods
Method Description
49
Javascript async/await
You use the async keyword with a function to represent that the function is an
asynchronous function. The async function returns a promise.
50
Example
async function f() {
console.log('Async function.');
return Promise.resolve(1);
}
f().then(function(result) {
console.log(result)
});
51
JavaScript await Keyword
he await keyword is used inside the async function to wait for the asynchronous
operation.
The use of await pauses the async function until the promise returns a result
(resolve or reject) value. For example,
52
Example: async + await
// a promise
let promise = new Promise(function (resolve, reject) {
setTimeout(function () {
resolve('Promise resolved')}, 4000);
});
// async function
async function asyncFunc() {
53
Error Handling
While using the async function, you write the code in a synchronous manner. And
you can also use the catch() method to catch the error. For example,
asyncFunc().catch(
// catch error and do something
)
The other way you can handle an error is by using try/catch block. For example,
54
Error handling example
// a promise
let promise = new Promise(function (resolve, reject) {
setTimeout(function () {
resolve('Promise resolved')}, 4000);
});
// async function
async function asyncFunc() {
try {
// wait until the promise resolves
let result = await promise;
console.log(result);
}
catch(error) {
console.log(error);
}
}
// calling the async function
55
asyncFunc(); // Promise resolved
Asynchronous JavaScript And
XML (AJAX)
The term for that kind of operation is Asynchronous JavaScript And XML (AJAX),
which uses the XMLHttpRequest object to communicate with the servers. It can
send and receive information in various formats, including JSON, XML, HTML, and
text files.
To get information from the server asynchronously we use:
● The fetch() API and
● Axios JS library
56
Asynchronous JavaScript And
XML (AJAX)
57
Axios
Axios is a Javascript library used to make http requests from node.js or
XMLHttpRequests from the browser, and it supports the Promise API that is native
to JS ES6.
60
Axios Interceptors
Axios provides interceptors for both requests and responses. In other words,
you can modify a request before sending it to an API or modify a response
object that’s been returned. It’s a powerful concept that allows the automation of
specific tasks.
You can use request interceptors to automatically add authorization headers.
Furthermore, response interceptors are useful for modifying the response object to
fit a different format. It’s even possible to intercept error responses and send them
to a monitoring tool.
axios.interceptors.request.use(config => {
config.name = 'my-axios-app'
console.log(`Sending ${config.method} request to: $
{config.url}`);
return config;
}, error => {
return Promise.reject(error);
}); 61
Error handling and Timeout
const url = 'https://jsonplaceholder.typicode.com/toodoos/1'
axios.get(url)
.then(response => console.log('good'))
.catch(error => console.error('error')) // enters catch method -> prints
404
---
const response = await axios.get('https://jsonplaceholder.typicode.com/todos/1', {
timeout: 1000
});
62
Request Options
baseUrl: if you specify a base URL, it’ll be prepended to any relative URL you use.
headers: an object of key/value pairs to be sent as headers.
params: an object of key/value pairs that will be serialized and appended to the
URL as a query string.
responseType: if you’re expecting a response in a format other than JSON, you can
set this property to arraybuffer, blob, document, text, or stream.
auth: passing an object with username and password fields will use these
credentials for HTTP Basic auth on the request.
63
The response
64