Method | Description | Syntax | Example |
---|---|---|---|
Array[x] | Stores elements that can be accessed by using the index (x). Can have 'obj.length' used in order to get number of items (array with 3 items.length will return the value of 3). Using 'obj.length = num' Will extend the array without adding anything to the new elements. |
|
|
push(x) | Adds x to the end of the array |
|
|
pop() | Removes the last element of an array and returns it as a value |
|
|
unshift(x) | Adds x to the start of the array |
|
|
An array is an ordered collection of values called elements. Each array element is stored in a numeric location called an index. An array is initialized by assigning an array variable with brackets [] containing comma-separated values.
Array elements may be of the same type or different types. Arrays increase in size as elements are added and decrease as elements are removed.
An array is an Array object that defines numerous methods for manipulating arrays. A method is a function that is attached to an object and operates on data stored in the object. Methods are called by prefacing the method with the object. Ex: myArray.method();.
The array property length contains the number of elements in the array. The length property is helpful for looping through an array using a for loop.
let groceries = ["bread", "milk", "peanut butter"];
// Display all elements in groceries array
for (i = 0; i < groceries.length; i++) {
console.log(i + " - " + groceries[i]);
}
The for-of loop is a simplified for loop that loops through an entire array. The array name is placed after the of keyword in a for-of loop. Each time through the loop, the next array element is assigned to the variable in front of the of keyword.
let groceries = ["bread", "milk", "peanut butter"];
// Display all elements in groceries array
for (let item of groceries) {
console.log(item);
}
The Array method forEach() also loops through an array. The forEach() method takes a function as an argument. The function is called for each array element in order, passing the element and the element index to the function.
let groceries = ["bread", "milk", "peanut butter"];
// Display all elements in groceries array
groceries.forEach(function(item, index) {
console.log(index + " - " + item);
});
An array can be passed to a function as an argument. A function may modify an array argument's elements.
The array methods indexOf() and lastIndexOf() search an array and return the index of the first found value or -1 if the value is not found. indexOf() searches from the beginning of the array to the end. lastIndexOf() searches from the end of the array to the beginning. Both functions take two arguments:
searchValue - The value to search for
startingPosition - Optional argument that indicates the index at which the search should begin (default is 0 for indexOf() and array.length - 1 for lastIndexOf())
let scores = [80, 92, 75, 64, 88, 92];
s = scores.indexOf(92); // 1
s = scores.indexOf(92, 2); // 5
s = scores.indexOf(100); // -1
s = scores.lastIndexOf(92); // 5
s = scores.lastIndexOf(92, 4); // 1
s = scores.lastIndexOf(50); // -1
The array method sort() sorts an array in ascending (increasing) order. sort()'s default behavior is to sort each element as a string using the string's Unicode values. Sorting by Unicode values may yield unsatisfactory results for arrays that store numbers. Ex: 10 is sorted before 2 because "10" is < "2" when comparing the Unicode values of "1" to "2".
The sort() method can sort elements in other ways by passing a comparison function to sort(). The comparison function returns a number that helps sort() determine the sorting order of the array's elements:
Returns a value < 0 if the first argument should appear before the second argument.
Returns a value > 0 if the first argument should appear after the second argument.
Returns 0 if the order of the first and second arguments does not matter.
Exploring further:
Array object from MDN
An object is an unordered collection of properties. An object property is a name-value pair, where the name is an identifier and the value is any data type. Objects are often defined with an object literal. An object literal (also called an object initializer) is a comma-separated list of property name and value pairs.
Assigning an object's property name with an anonymous function creates a method. Methods access the object's properties using the keyword this, followed by a period, before the property name. Ex: this.someProperty.
Defining a method in an object literal
let book = {
title: "Quiet",
author: {
firstName: "Susan",
lastName: "Cain"
},
// Define a method
getAuthorName() {
return this.author.firstName + " " + this.author.lastName;
}
};
// Call a method that returns "Susan Cain"
let name = book.getAuthorName();
Defining a method for an existing object
let book = {
title: "Quiet",
author: {
firstName: "Susan",
lastName: "Cain"
}
};
// Define a method
book.getAuthorName = function() {
return this.author.firstName + " " + this.author.lastName;
};
// Call a method that returns "Susan Cain"
let name = book.getAuthorName();
An object property may need to be computed when retrieved, or setting a property may require executing some code to perform data validation. The get and set keywords define getters and setters for a property.
For those familiar with how this works in other languages, this works a little differently in JavaScript. The getter and setter have the same name, forming an accessor property so that 'obj.attribute' when used as a variable retrieves the value, but when used as 'obj.attribute = x' will pass through the value of x. Although the standard usage/syntax of getters and setters can also be used.
A getter is a function that is called when an object's property is retrieved. Syntax to define a getter:
get property() { return someValue; }.
A setter is a function that is called when an object's property is set to a value. Syntax to define a setter:
set property(value) { this.var = value }.
An accessor property is an object property that has a getter or a setter or both.
let rectangle = {
width: 5,
height: 8,
get area() {
return this.width * this.height;
},
set area(value) {
// Set width and height to the square root of the value
this.width = Math.sqrt(value);
this.height = this.width;
}
};
let area = rectangle.area; // Calling getter returns 40
rectangle.area = 100; // Calling setter sets width and height to 10
console.log(rectangle.width); // 10
JavaScript data types can be divided into two categories: primitives and references
A primitive is data that is not an object and includes no methods. Primitive types include: boolean, number, string, null, and undefined.
A reference is a logical memory address. Only objects are reference types.
Assigning a variable with a primitive creates a copy of the primitive. Ex: If y is 2, then x = y; means x is assigned with a copy of y. Assigning a variable with a reference creates a copy of the reference. Ex: If y refers to an object, then x = y; means x is assigned with a copy of y's reference. Both x and y refer to the same object.
When a primitive is passed to a function, the parameter is assigned a copy of the argument. Changing the parameter does not change the argument.
When an object is passed to a function, the parameter is also assigned a copy of the argument. However, the parameter and argument are both a reference to the same object. Changing the parameter reference to a new object does not change the argument, but changing the parameter's properties does change the argument's properties.
All primitives, except for null and undefined, have equivalent objects that wrap the primitive values and provide methods for interacting with the primitives. Ex: A string primitive has a String class that provides various methods for manipulating a string. Calling "abc".toUpperCase() converts the primitive string into a String object, calls the method, and returns the string primitive "ABC".
Exploring further:
Working with objects from MDN
A map or associative array is a data structure that maps keys to values. Each key/value pair in a map is called an element.
JavaScript objects can be used as maps, in which the key is the object property and the value is the property's value. When an object is used as a map, individual elements are accessed by key using brackets. Ex: myMap["key"].
You can also stack / add layers to your maps such as in the example below
For example if you want to access Dave's email you write 'contacts["Dave"].email'
The for-in loop iterates over an object's properties in arbitrary order and is ideal for looping through an object map's elements. The for-in loop declares a variable on the left side of the in keyword and an object on the right. In each iteration, the variable is assigned with each of the object's properties.
Other common operations performed on object maps include:
Get number of elements. The Object.keys() method returns an array of an object's property names. The array's length property returns the number of elements in the object map.
Check for key. The in operator returns true if an object contains the given property and returns false otherwise.
Remove element. The delete operator removes a key/property from a map or object.
The Map object is a newer alternative to using objects for storing key/value pairs. Common methods and properties of the Map object include:
The set(key, value) method sets a key/value pair. If the key is new, a new element is added to the map. If the key already exists, the new value replaces the existing value.
The get(key) method gets a key's associated value.
The has(key) method returns true if a map contains a key, false otherwise.
The delete(key) method removes a map element.
The size property is the number of elements in the map.
The for-of loop, which is often used to loop through an array, is ideal for looping through a Map. Each of the map's key/value pairs are assigned to the [key, value] variables declared in the for-of loop, as illustrated in the animation below.
Exploring further:
Map objects from MDN
The String object defines methods to manipulate strings, extract substrings, test for string inclusion, etc. A string literal (a string in "quotes") is automatically converted into a String object when a String method is invoked.
The String method charAt() returns the character at the specified index as a string. Ex: "test".charAt(1) returns the character "e" at index 1. The String property length returns the number of characters in a string. Ex: "test".length returns 4. Calling charAt() with an index ≥ the string's length returns an empty string.
The String object provides methods to search and replace strings:
The indexOf() method returns the index of the search string's first occurrence inside the String object or -1 if the search string is not found.
The lastIndexOf() method returns the index of the search string's last occurrence inside the String object or -1 if the search string is not found.
The replace() method replaces one string with another and returns the string with the replacement string inside.
indexOf() / lastIndexOf()
Variable.replace("", "")
A variety of other String methods exist. Some of the common methods are summarized in the table below.
A template literal is a string literal enclosed by the back-tick (`) that allows embedding expressions with a dollar sign and braces (${expression}). Ex: `test ${1 + 2}` evaluates to "test 3". Template literals replace the need to produce a string with string concatenation.
Exploring further:
String object from MDN
Template literals (Template strings) from MDN
A Date object represents a single moment in time, based on the number of milliseconds since the Unix Epoch (January 1, 1970 UTC). UTC (Coordinated Universal Time), also known as GMT (Greenwich Mean Time), is a 24-hour time standard. The Date object is created with the new operator and a constructor. A constructor is a function that creates an instance of an object.
The Date object provides a number of methods to get and set Date properties.
Exploring further:
Date object from MDN
Introduction to the Math object
'Function | Description |
---|---|
Math.PI | Value of π, approximately 3.142 |
Math.E | Euler's number, approximately 2.718 |
Math.LN2 | Natural logarithm of 2, approximately 0.693 |
Math.LOG10E | Base 10 logarithm of E, approximately 0.434 |
Math.SQRT2 | Square root of 2, approximately 1.414 |
The Math object has a range of trigonometric methods, including sin(), cos(), and tan(), and general calculation methods, including log() and pow(). Some commonly used Math methods are summarized in the table below.
Many applications, especially games and simulations, need random numbers to simulate random processes. The Math.random() method returns a pseudo-random number ≥ 0 and < 1. A pseudo-random number is a number generated by an algorithm that approximates randomness, but is not truly random.
The figure below shows a getRandomNumber() function that performs the necessary calculations to generate a random integer between two integers.
Exploring further:
Math object from MDN
Introduction to Randomness and Random Numbers from random.org
An exception is an error that disrupts the normal flow of program execution. When an exception occurs, a program may need to execute code to handle the error. Ex: Display an error message, call a function, or shutdown. Exception handling is the process of catching and responding to an exception.
Calling a method that does not exist:
The throw statement throws a user-defined exception. Syntax: throw expression. Ex: throw "number is negative" throws an exception with a string value.
A program halts when an exception is thrown unless a try-catch statement is used to catch/handle the exception. A try-catch statement has a try block to execute code that may throw an exception and a catch block that executes when an exception is thrown.
A finally block may follow a try or catch block. The finally block executes regardless of whether an exception was thrown or not.
Developers use the finally block for any operations that must be executed, whether or not an exception was thrown. Ex: Releasing resources, closing files, and rolling back failed database transactions.
Using finally without a catch will skip the rest of the method
Developers find finally blocks especially helpful when the code in the catch block might throw an exception, because the finally block will execute even if an exception is thrown in the catch block.
finally with catch
The throw statement can throw any expression, but developers commonly throw an Error object. The Error object represents a runtime error, which is an error that occurs when the program is executing. An Error object has two properties:
name - The error's name.
message - The error's message.
The Error constructor takes a message parameter. Ex: err = new Error("My error message.");
JavaScript defines several other Error constructors, including:
RangeError - Thrown when a numeric variable or parameter is outside the valid range.
InternalError - Thrown when an internal error occurs in the JavaScript interpreter.
TypeError - Thrown when a variable or parameter is not the expected data type.
Exploring further:
try...catch from MDN
Error object from MDN
typeof operator from MDN
JavaScript allows webpages to be more interactive. JavaScript can execute in response to user interactions and alter the contents of the webpage. Ex: A user clicks on a button, and JavaScript executes and changes the color of the webpage.
The Document Object Model (or DOM) is a data structure that represents all parts of an HTML document. The JavaScript object document represents the entire DOM and is created from the document's HTML. Changes made to document are reflected in the browser presentation and/or behavior.
A webpage's JavaScript code appears in the <script> element and is executed by the browser's JavaScript engine.
You can use document.writeln("text") in order to directly write code to the HTML document.
JavaScript running in a web browser has access to the window object, which represents an open browser window. In a tabbed browser, each tab has a window object. The document object is a property of the window object and can be accessed as window.document or just document. Other properties of the window object include:
window.location is a location object that contains information about the window's current URL. Ex: window.location.hostname is the URL's hostname.
window.navigator is a navigator object that contains information about the browser. Ex: window.navigator.userAgent returns the browser's user agent string.
window.innerHeight and window.innerWidth are the height and width in pixels of the window's content area. Ex: window.innerWidth returns 600 if the browser's content area is 600 pixels wide.
The window object defines some useful methods:
window.alert() displays an alert dialog box. Ex: window.alert("Hello") displays a dialog box with the message "Hello".
window.confirm() displays a confirmation dialog box with OK and Cancel buttons. confirm() returns true if OK is pressed and false if Cancel is pressed. Ex: window.confirm("Are you sure?") displays a dialog box with the question.
window.open() opens a new browser window. Ex: window.open("https://www.twitter.com/") opens a new browser that loads the Twitter webpage.
Modern browsers provide a console that allows the JavaScript code to produce informational and debugging output for the web developer, which does not affect the functionality or presentation of the webpage. By default, the console is not visible. The console is viewable in Chrome by pressing Ctrl+Shift+J in Windows/Linux or Cmd+Opt+J on a Mac.
When a syntax error is present in JavaScript code or a run-time error occurs, the error is only made visible in the console. The figure below shows the syntax error created when the developer accidentally typed Document.writeln() with a capital "D". The console appears underneath the webpage. Good practice is to leave the console open while writing and testing JavaScript code.
The browser provides a console object with a defined set of methods, or API, that the console object supports. An API (Application Programming Interface) is a specification of the methods and objects that defines how a programmer should interact with software components. The console API includes the following methods:
console.log() displays informational data to the console.
console.warn() displays warnings to the console. The browser usually has a special indicator to differentiate a warning from the standard log message. Ex: A yellow warning box.
console.error() displays errors to the console. The browser usually has a special indicator to differentiate an error from a warning or the standard log message. Ex: A red error box.
console.dir() displays a JavaScript object to the console. The browser usually supports a method for compactly representing the object. Ex: A hierarchical tree representation allowing a developer to expand and collapse the object contents.
Including JavaScript directly within an HTML file is common practice when using small amounts of JavaScript. However, writing JavaScript directly within the document may lead to problems as a webpage or website gets larger.
Good practice is to use <script> elements to load JavaScript from an external file rather than writing the JavaScript directly within the HTML file. The <script> element's src attribute specifies a JavaScript file to load.
<script src="bootstrap.js"></script>
A common error when loading an external JavaScript file is to forget the closing tag or trying to use a self-closing <script /> tag as in <script src="bootstrap.js" />. All modern browsers require a closing </script> tag. You should also not write your code within your external <script> tag as it does not work / is not intended to be used that way.
Although the <script> element can be included anywhere in the head or body, good practice is to include the <script> element in the head with the async or defer attributes set.
The <script> element's async attribute allows the browser to process the webpage concurrently with loading and processing the JavaScript.
The <script< element's defer attribute allows the browser to load the webpage concurrently with loading the JavaScript, but the JavaScript is not processed until the webpage is completely loaded.
To reduce the amount of JavaScript that must be downloaded from a web server, developers often minify a website's JavaScript. Minification or minimization is the process of removing unnecessary characters (like whitespace and comments) from JavaScript code so the code executes the same but with fewer characters. Minification software may also rename identifiers into shorter ones to reduce space. Ex: let totalReturns = 10; may be converted into let a=10;.
Minified JavaScript is typically stored in a file with a ".min.js" file extension. An example of minified code from the Bootstrap project is shown below.
// Excerpt from bootstrap.min.js
a.fn.button=b,a.fn.button.Constructor=c,a.fn.button.noConflict=function(){
return a.fn.button=d,this},a(document).on("click.bs.button.data-api",
'[data-toggle^="button"]',function(c){let d=a(c.target).closest(".btn");
b.call(d,"toggle"),a(c.target).is('input[type="radio"],
A JavaScript obfuscator is software that converts JavaScript into an unreadable form that is very difficult to convert back into readable JavaScript. Developers obfuscate a website's JavaScript to prevent the code from being read or re-purposed by others. Obfuscated code may also be minified and appear in a ".min.js" file.
Exploring further:
Window object from MDN
Console object from MDN
async vs defer attributes from Growing with the Web
JavaScript minifiers from javascript.minifier.com and jscompress.com
JavaScript obfuscators from javascriptobfuscator.com and JS-obfus
The Document Object Model (DOM) is a data structure corresponding to the HTML document displayed in a web browser. A DOM tree is a visualization of the DOM data structure. A node is an individual object in the DOM tree. Nodes are created for each element, the text between an element's tags, and the element's attributes.
The root node is the node at the top of the DOM.
A child node is the node directly under another node. A node can have zero, one, or more child nodes (children).
A parent node is the node directly above another node. All nodes, except the root node, have one parent node.
An idealized representation of the DOM tree excludes text nodes that only contain whitespace. However, a web developer occasionally needs to know the complete DOM tree, which includes whitespace as shown in the example below.
This is why when you inspect element / dev tools in your browser the code may differ from the source code, it is not showing you the code, it is showing you the DOM
You can access the DOM view Ctrl+Shift+C on Windows or Ctrl+Option+C on a Mac.
JavaScript is commonly used to search the DOM for a specific node or set of nodes and then change the nodes' attributes or content. Ex: In an email application, the user may click a Delete button to delete an email. The JavaScript must search the DOM for the node containing the email's contents and then change the contents to read "Email deleted".
The document object provides five primary methods that search the DOM for specific nodes:
The document.getElementById() method returns the DOM node whose id attribute is the same as the method's parameter.
Ex: document.getElementById("early_languages") returns the p node in the HTML below.
The document.getElementsByTagName() method returns an array of all the DOM nodes whose type is the same as the method's parameter.
Ex: document.getElementsByTagName("li") returns an array containing the four li nodes from in the HTML below.
The document.getElementsByClassName() method returns an array containing all the DOM nodes whose class attribute matches the method's parameter.
Ex: document.getElementsByClassName("traditional") returns an array containing the ol node with the class attribute matching the word traditional.
The document.querySelectorAll() method returns an array containing all the DOM nodes that match the CSS selector passed as the method's parameter.
Ex: document.querySelectorAll("li a") returns an array containing the two anchor nodes in the HTML below.
The document.querySelector() method returns the first element found in the DOM that matches the CSS selector passed as the method's parameter. querySelector() expects the same types of parameters as querySelectorAll() but only returns the first element found while navigating the DOM tree in a depth-first traversal.
Ex: document.querySelector("li") returns the li node about Fortran.
A DOM search method name indicates whether the method returns one node or an array of nodes. If the method name starts with "getElements" or ends in "All", then the method returns an array, even if the array contains one node or is empty. getElementById() and querySelector() either return a single node or null if no node matches the method arguments.
Technically, getElementsByTagName() and getElementsByClassName() return an HTMLCollection, and querySelectorAll() returns a NodeList. HTMLCollection is an interface representing a generic collection of elements. A NodeList is an object with a collection of nodes. HTMLCollection and NodeList both act like an array. Both have a length property, and elements can be accessed with braces. Ex: elementList[0] is the first element in an HTMLCollection or NodeList.
After searching the DOM for an element, JavaScript may be used to examine the element's attributes or to change the attributes. By modifying attributes, JavaScript programs can perform actions including:
Change which image is displayed by modifying an img element's src attribute.
Determine which image is currently displayed by reading the img element's src attribute.
Change an element's CSS styling by modifying an element's style attribute.
Every attribute for an HTML element has an identically named property in the element's DOM node. Ex: <a href="https://www.nasa.gov/" id="nasa_link">NASA</a> has a corresponding DOM node with properties named href and id. Each attribute property name acts as both a getter and a setter.
Getter: Using the property name to read the value allows a program to examine the attribute's value. Ex: nasaUrl = document.getElementById("nasa_link").href assigns nasaUrl the string "https://www.nasa.gov/" from the anchor element's href attribute.
Setter: Writing to a property allows a program to modify the attribute, which is reflected in the rendered webpage. Ex: document.getElementById("nasa_link").href = "https://www.spacex.com/" changes the element's hyperlink to the SpaceX URL.
An element's attribute can be removed using the element method removeAttribute(). Ex: document.getElementById("nasa_link").removeAttribute("href") removes the link from the anchor element so that clicking on the HTML element no longer performs an action.
Overall: 'selector.removeAttribute("attribute name")' removes an attribute from an element and 'selector.attrubute = value' adds an attribute
After searching the DOM for an element, JavaScript may be used to examine or change the element's content.
Two common properties are used to get or set an element's content:
The textContent property gets or sets a DOM node's text content. Ex: document.querySelector("p").textContent = "$25.99"; changes the paragraph to <p>$25.99</p>.
The innerHTML property gets or sets a DOM node's content, including all of the node's children, using an HTML-formatted string. Ex: document.querySelector("p").innerHTML = "<strong>$25.99</strong>"; changes the paragraph to <p><strong>$25.99</strong></p>.
The innerHTML property uses an internal parser to create any new DOM nodes. textContent, however, only creates or changes a single text node. For setting an element's text, textContent is somewhat faster than innerHTML because no HTML parsing is performed.
The nodeValue property gets or sets the value of text nodes. As the DOM tree represents textual content separately from HTML elements, the textual content of an HTML element is the first child node of the HTML element's node. So, to access the textual content of an HTML element within the DOM, firstChild.nodeValue is used to access the value of the HTML's element's first child.
Ex: document.getElementById("saleprice").firstChild.nodeValue = "$25.99":
Gets the DOM node for the element with id "saleprice".
Uses firstChild to access the textual content node for the element.
Uses nodeValue to update the content.
The innerText property gets or sets a DOM node's rendered content. innerText is similar to textContent, but innerText is aware of how text is rendered in the browser. Ex: In
Testing one
, textContent returns "Testing one" with spaces, but innerText returns "Testing one" with the spaces collapsed into a single space.Exploring further:
Document Object Model (DOM) from MDN
The JavaScript object document.documentElement is the root of the DOM tree. Ex: let html = document.documentElement; assigns the html variable with the HTML document's root node.
DOM nodes have properties for accessing a node's parent, children, and siblings:
The parentNode property refers to the node's parent. Ex: In the figure below, the ol node is the parentNode for all li nodes.
The childNodes property is an array-like collection of objects for each of the node's children. Ex: In the figure below, the li nodes and whitespace text nodes are the ol node's childNodes.
The children property is similar to the childNodes except the array contains only element nodes and no text nodes. Ex: In the figure below, the li nodes are the ol node's children.
The nextElementSibling property refers to the element node with the same parent following the current node in the document. Ex: In the figure below, the ol node is the p node's nextElementSibling.
The previousElementSibling property refers to the element node with the same parent preceding the current node in the document. Ex: In the figure below, the p node is the ol node's previousElementSibling.
A common error is to use the childNodes property instead of the children property when iterating through the items of a list. The children property only contains the list items, while the childNodes property also contains the whitespace text nodes between the list items.
Various DOM node methods can change a node's location within the DOM or remove nodes:
The appendChild() method appends a DOM node to the object's child nodes. The code below moves the ordered list's first list item to the last list item of the same ordered list.
ol = document.getElementsByTagName("ol")[0];
li = ol.getElementsByTagName("li")[0];
ol.appendChild(li);
The insertBefore() method inserts a DOM node as a child node before an object's existing child node. The code below moves the ordered list's first list item before the fourth list item.
ol = document.getElementsByTagName("ol")[0];
items = ol.getElementsByTagName("li");
ol.insertBefore(items[0], items[3]);
The removeChild() method removes a node from the object's children. The most common usage pattern is to get a DOM node, n, and call removeChild() on n's parent passing n as an argument. Ex: n.parentNode.removeChild(n)
The following methods are for creating new nodes or duplicating existing nodes:
The document method createElement() returns a new element node, created from a string argument that names the HTML element. Ex: document.createElement("p") creates a new paragraph node.
The document method createTextNode() returns a new text node containing the text specified by a string argument. Ex: document.createTextNode("Hello there!") creates the text node with "Hello there!", which can then be appended to an element node.
The node method cloneNode() returns an identical copy of a DOM node. The method's boolean argument indicates whether the method should also clone the node's children. Ex: x.cloneNode(true) creates an identical tree rooted at x, but x.cloneNode(false) creates only a single node identical to x. A common error is to forget to modify any id attributes in the cloned tree. The cloneNode() method does not ensure that new nodes have unique id attributes.
After creating or cloning a node, the node does not appear in the webpage until the node is attached to the DOM tree. A programmer must use appendChild() or insertBefore() to add the new node to the existing DOM tree.
Exploring further:
Document Object Model (DOM) from MDN
An event is an action, usually caused by a user, that the web browser responds to. Ex: A mouse movement, a key press, or a network response from a web server. Typically, the occurrence and timing of an event are unpredictable, since the user or web server can perform an action at any time.
Event-driven programming is a programming style where code runs only in response to various events. Code that runs in response to an event is called an event handler or event listener.
The web browser supports event-driven programming to simplify handling the many events a webpage must process. When an event happens, the browser calls the event's specified handlers. The web browser internally implements the code for detecting events and executing event handlers.
The example below modifies an input's style property, which sets the element's inline CSS styles. The input's border color changes colors when the input receives the focus or when focus is removed.
Event | Description |
---|---|
click | Caused by a mouse click. |
mouseover | Caused by mouse entering the area defined by an HTML element. |
mouseout | Caused by mouse exiting the area defined by an HTML element. |
mousemove | Caused by mouse moving within the area defined by an HTML element. |
keydown | Caused by the user pushing down a key on the keyboard. |
keyup | Caused by the user releasing a key on the keyboard. |
The following are events for which web developers commonly write handlers:
A change event is caused by an element value being modified. Ex: Selecting an item in a radio button group causes a change event.
An input event is caused when the value of an input or textarea element is changed.
A load event is caused when the browser completes loading a resource and dependent resources. Usually load is used with the body element to execute code once all the webpage's CSS, JavaScript, images, etc. have finished loading.
A DOMContentLoaded event is caused when the HTML file has been loaded and parsed, although other related resources such as CSS, JavaScript, and image files may not yet be loaded.
A focus event is caused when an element becomes the current receiver of keyboard input. Ex: Clicking in an input field causes a focus event.
A blur event is caused when an element loses focus and the element will no longer receive future keyboard input.
A submit event is caused when the user submits a form to the web server.
Handlers are written in three ways:
Embedding the handler as part of the HTML. Ex: <button onclick="clickHandler()">Click Me</button> sets the click event handler for the button element by using the onclick attribute. The attribute name used to register the handler adds the prefix "on" to the event name. Ex: The attribute for a mousemove event is onmousemove. Embedding a handler in HTML mixes content and functionality and thus should be avoided whenever possible.
Setting the DOM node event handler property directly using JavaScript. Ex: document.querySelector("#myButton").onclick = clickHandler sets the click event handler for the element with an id of "myButton" by overwriting the onclick JavaScript property. Using DOM node properties is better than embedding handlers within the HTML but has the disadvantage that setting the property only allows one handler for that element to be registered.
Using the JavaScript addEventListener() method to register an event handler for a DOM object. Ex: document.querySelector("#myButton").addEventListener("click", clickHandler) registers a click event handler for the element with the id "myButton". Good practice is to use the addEventListener() method whenever possible, rather than using element attributes or overwriting JavaScript properties. The addEventListener() method allows for separation of content and functionality and allows multiple handlers to be registered with an element for the same event.
Every handler has an optional event object parameter that provides details of the event. Ex: For a keyup event, the event object indicates which key was pressed and released, or for a click event, which element was clicked.
In the image below, keyupHandler() uses event.target to access the text box object where the keyup event occurred. Inside an event handler, the this keyword refers to the element to which the handler is attached. So event.target and this both refer to the text box object in the event handler.
When an event occurs, the browser follows a simple DOM traversal process to determine which handlers are relevant and need to be called. The DOM traversal process has three phases: capturing, at target, and bubbling.
In the event capturing phase, the browser traverses the DOM tree from the root to the event target node, at each node calling any event-specific handlers that were explicitly registered for activation during the capturing phase.
In the at target phase, the browser calls all event-specific handlers registered on the target node.
In the event bubbling phase, the browser traverses the DOM tree from the event target node back to the root node, at each node calling all event-specific handlers registered for the bubbling phase on the current node.
The optional third parameter for the addEventListener() method indicates whether the handler is registered for the capturing phase or bubbling phase. If the third parameter is false or not specified, or if the event handler is registered using any other mechanism, the browser registers the handler for the event bubbling phase. If the parameter is true, the browser registers the handler for the capturing phase.
Some events do not bubble, such as blur, focus, and change. When a non-bubbling event occurs, the browser will follow the event capturing phase, the at target phase, and then stop.
This is really annoying to describe consisely in text so look at this website for more details
The event capturing and bubbling process can be stopped by calling the stopPropagation() method on the event object provided to the handler. Once stopPropagation() is called, the browser stops the traversal process but still calls relevant registered handlers on the current node.
A web developer may want to prevent the browser from using a built-in handler for an event. Ex: Whenever a user clicks a form's submit button, the web browser sends the form data to the web server. The event object's preventDefault() method stops the web browser from performing the built-in handler. The built-in handlers that are often prevented are clicking elements, submitting forms, and moving the mouse into or out of an element.
Exploring further:
Event reference from MDN
EventTarget.addEventListener() from MDN
Event flow tutorial from Java2s