JavaScript – HTML DOM

JavaScript – Document Object Model or DOM ”; Previous Next The HTML DOM allows JavaScript to access and modify the content of HTML elements. JavaScript can change all HTML elements, attributes, CSS styles in the page. JavaScript can also add, remove the HTML elements and attributes. Using JavaScript, we can even create new events in the page. Every web page resides inside a browser window which can be considered as an object. A Document object represents the HTML document that is displayed in that window. The Document object has various properties that refer to other objects which allow access to and modification of document content. What is DOM? The DOM is an acronym for the Document Object Model. It is a programming interface for Core, XML, and HTML DOM. It is a W3C (World Wide Web Consortium) standard. The DOM defines the logical or tree-like structure of the web page or document. In the tree, each branch ends in a node, and each node contains objects. DOM methods allow us programmatic access to the tree. Using the DOM methods, you can change the document”s structure, content or style. What is HTML DOM? HTML creates the web page”s structure, and JavaScript adds interaction to the web page by manipulating the HTML elements. JavaScript can’t interact directly with HTML elements. So, whenever a web page loads in the browser, it creates a DOM. So, the document object represents the HTML document displayed in that window. Furthermore, each iframe in the webpage creates a new DOM. The Document object has various properties that refer to other objects that allow access to and modify document content. The way a document content is accessed and modified is called the Document Object Model, or DOM. The Objects are organized in a hierarchy. This hierarchical structure applies to the organization of objects in a Web document. Window object − It represents the current window of the browser. It also works as a global object for the browser window. It is at the top of the hierarchy. It is the outmost element of the object hierarchy. Document object − Each HTML document that gets loaded into a window becomes a document object. The document contains the contents of the page. It is used to access and modify the elements of the web page. Form object − Everything enclosed in the <form>…</form> tags sets the form object. Form control elements − The form object contains all the elements defined for that object, such as text fields, buttons, radio buttons, and checkboxes. Here is a simple hierarchy of a few important objects − There are several DOMs in existence. The following sections explain each of these DOMs in detail and describe how you can use them to access and modify document content. The Legacy DOM − This is the model which was introduced in early versions of JavaScript language. It is well supported by all browsers, but allows access only to certain key portions of documents, such as forms, form elements, and images. The W3C DOM − This document object model allows access and modification of all document content and is standardized by the World Wide Web Consortium (W3C). This model is supported by almost all the modern browsers. There are three different types of the DOM according to the W3C. Core DOM − It is a standard model for all document types. HTML DOM − It is a standard model for HTML documents. XML DOM − It is a standard model for XML documents. Why is DOM required? As discussed above, when a web page is loaded into the browser window, it becomes a document object. After that, JavaScript can access the HTML elements and perform the other operations on them. It means JavaScript can interact with the web page using the HTML DOM. For example, JavaScript can perform the below operations on HTML elements using the document object. Access HTML elements Replace HTML elements Add New HTML elements Delete HTML elements Change CSS of HTML elements Change attributes of HTML elements Add animation to HTML elements Add events to HTML elements However, there are other uses of the document object, which we will cover in upcoming chapters. Print Page Previous Next Advertisements ”;

JavaScript – Mouse Events

JavaScript – Mouse Events ”; Previous Next JavaScript mouse events allow users to control and interact with web pages using their mouse. These events trigger specific functions or actions in response to user clicks, scrolls, drags, and other mouse movements. To handle mouse events in JavaScript, you can use the addEventListener() method. The addEventListener() method takes two arguments: the event type and the event handler function. The event type is the name of the event that you want to handle, and the event handler function is the function that will be called when the event occurs. In web development, JavaScript provides a powerful mechanism to respond to user interactions with the mouse through a set of events. These events enable developers to create dynamic and interactive web applications by capturing and handling various mouse-related actions. Common Mouse Events Following are the most common JavaScript mouse events: Mouse Event Description Click When an element experiences the press of a mouse button, it triggers the click event. Double Click The dblclick event fires upon the rapid double-clicking of a mouse button. Mouse Down and Mouse Up The initiation of a mouse click triggers the ”mousedown” event, while the completion of that click causes the ”mouseup” event to occur. Mouse Move When the mouse pointer moves over an element, it triggers the ”mousemove” event; this event supplies developers with positional information about the mouse. This data empowers them to devise responsive interfaces that are rooted in dynamic mouse movements. Context Menu When the user attempts to open the context menu, typically by right-clicking, they trigger the contextmenu event. This event allows developers to customize or inhibit default behaviour of the context menu. Wheel When the mouse wheel rotates, it fires the ”wheel event”; this particular event commonly manifests in implementing features, notably zooming or scrolling. Drag and Drop Events like dragstart, dragend, dragover, dragenter, dragleave, and drop are associated with drag-and-drop functionality. They allow developers to create interactive interfaces for dragging elements within a web page. Example : Click Event In this example we demonstrate the click event. When the button is clicked, it prints an appropriate message to the console message i.e. “Clicked!”. This event is often used while submitting forms. <!DOCTYPE html> <html> <head> <title>Click Event Example</title> </head> <body> <button id=”clickButton”>Click me!</button> <p id = “output”></p> <script> const clickButton = document.getElementById(”clickButton”); const outputDiv = document.getElementById(“output”); clickButton.addEventListener(”click”, function(event) { outputDiv.innerHTML += ”Clicked!”+ JSON.stringify(event) + “<br>”; }); </script> </body> </html> Example: Double Click Event The dblclick event operates in this example, triggering upon a double-click of the designated button. We attach the event listener to an element with “doubleClickButton” as its id. A user”s double-click on the button prompts a function that logs a console message, confirming their interaction with it. <!DOCTYPE html> <html> <head> <title>Double Click Event Example</title> </head> <body> <button id=”doubleClickButton”>Double-click me!</button> <p id = “output”></p> <script> const doubleClickButton = document.getElementById(”doubleClickButton”); const outputDiv = document.getElementById(“output”); doubleClickButton.addEventListener(”dblclick”, function(event) { outputDiv.innerHTML += ”Double-clicked!” + JSON.stringify(event) + “<br>”; }); </script> </body> </html> Example: Mouse Down and Mouse Up Events The use of the mousedown and mouseup events is exemplified in this scenario: both events apply to a <div> element identified as “mouseUpDownDiv.” Two distinct event listeners are established; one responds to the down action of the mouse button, while another reacts upon release or up motion of said button. Upon pressing over the designated div (mousedown), a message indicating that the user has depressed their mouse button appears within your console log. When the user releases the mouse button (mouseup), we also log another message to indicate that the mouse button is up. <!DOCTYPE html> <html> <head> <title>Mouse Down and Mouse Up Events Example</title> </head> <body> <div id=”mouseUpDownDiv” style=”width: 600px; height: 100px; background-color: lightblue;”> Please perform mouse down and up event any where in this DIV. </div> <p id = “output”></p> <script> const mouseUpDownDiv = document.getElementById(”mouseUpDownDiv”); const outputDiv = document.getElementById(“output”); mouseUpDownDiv.addEventListener(”mousedown”, function(event) { outputDiv.innerHTML += ”Mouse button down!” + JSON.stringify(event) + “<br>”; }); mouseUpDownDiv.addEventListener(”mouseup”, function(event) { outputDiv.innerHTML += ”Mouse button up!” + JSON.stringify(event) + “<br>”; }); </script> </body> </html> Example: Mouse Move Event In this instance, we employ the mousemove event to monitor the mouse pointer”s movement over a specific <div> element identified as “mouseMoveDiv.” The handler function extracts clientX and clientY properties from an event object that represents X-Y coordinates of said pointer. Subsequently, these are logged into console; thus offering real-time feedback on where exactly within our designated div area is the user positioning their cursor. <!DOCTYPE html> <html> <head> <title>Mouse Move Event Example</title> </head> <body> <div id=”mouseMoveDiv” style=”width: 600px; height: 200px; background-color: lightgreen;”> Please move you mouse inside this DIV.</div> <p id = “output”></p> <script> const mouseMoveDiv = document.getElementById(”mouseMoveDiv”); const outputDiv = document.getElementById(“output”); mouseMoveDiv.addEventListener(”mousemove”, function(event) { const x = event.clientX; const y = event.clientY; outputDiv.innerHTML += `Mouse moved to (${x}, ${y})` + JSON.stringify(event) + “<br>”; }); </script> </body> </html> Example: Wheel Event This example showcases the wheel event, activated when the mouse wheel is rotated. The event listener is attached to a <div> element with the id “wheelDiv.” When the user rotates the mouse wheel over this div, the associated function logs a message to the console, indicating that the mouse wheel has been rotated. <!DOCTYPE html> <html> <head> <title>Wheel Event Example</title> </head> <body> <div id=”wheelDiv” style=”width: 600px; height: 200px; background-color: palevioletred;”> Please bring the curser inside this DIV and rotate the wheel of mouse.</div> <p id = “output”></p> <script> const wheelDiv = document.getElementById(”wheelDiv”); const outputDiv = document.getElementById(“output”); wheelDiv.addEventListener(”wheel”, function(event) { outputDiv.innerHTML += ”Mouse wheel rotated!”+ event + “<br>”; }); </script> </body> </html> Print Page Previous Next Advertisements ”;

JavaScript – DOM Forms

JavaScript – DOM Forms ”; Previous Next The DOM Forms The HTML DOM document forms are used to get the data from the users. In JavaScript, you can use the ”forms” collection of the ”document” object to access all <form> elements of the HTML document. You can access all forms elements of particular forms and manipulate them. Using JavaScript, you can validate the form values, handle the form data submission, etc. Syntax Follow the syntax below to use the ”forms” collection to manipulate the forms of the DOM. document.forms; Here, ”forms” is a property of the ”document” object. Properties of ”forms” Collection Property Description length It represents the number of <form> elements in the HTML document. Methods of ”forms” Collection Method Description [index] To get the particular <form> element from the 0-based index of the collection of HTML forms. item(index) To get the particular <form> element from the 0-based index of the collection of HTML forms. namedItem(id) To get the <form> element with a particular id. Return value The document.forms returns the collection of all forms in the same order as they are present in the HTML document. Example: Finding total <form> elements in the HTML document) In the below code, we use the ”length” property of the ”forms” collection to find the number of existing forms in the HTML document. <html> <body> <form> <input type = “text” name = “first” id = “first” value = “First Name”> </form> <form> <input type = “text” name = “second” id = “second” value = “Last Name”> </form> <form> <input type = “text” name = “third” id = “third” value = “Contact”> </form> <div id = “output”>Total number of forms in the HTML document is: </div> <script> document.getElementById(”output”).innerHTML += document.forms.length; </script> </body> </html> Example: Get the id of all <form> elements In the below code, we access each form using its index and use the ”id” property to get the id of a particular form. <html> <body> <form id = “form1”> <label for = “first”> Fruit Name: </label> <input type = “text” name = “first” id = “first”> </form> <form id = “form2”> <label for = “second”> Price: </label> <input type = “text” name = “second” id = “second”> </form> <form id = “form3”> <label for = “third”> Color: </label> <input type = “text” name = “third” id = “third”> </form> <div id = “output”> </div> <script> document.getElementById(”output”).innerHTML = “Id of the first form is: ” + document.forms[0].id + “<br>” + “Id of the second form is: ” + document.forms[1].id + “<br>” + “Id of the third form is: ” + document.forms[2].id; </script> </body> </html> Example: Get particular form using its id and namedItem() method In the code below, we used the namedItem() method by taking the ”forms” collection as a reference to get a form with a particular id. <html> <body> <form id = “form1”> <label for = “first”> First Name </label> <input type = “text” name = “first” id = “first”> </form> <form id = “form2”> <label for = “second”> Last Name </label> <input type = “text” name = “second” id = “second”> </form> <div id = “output”>The innerHTML of the form element having id equal to form2 is: </div> <script> const output = document.getElementById(”output”); output.innerHTML += document.forms.namedItem(”form2”).innerHTML; </script> </body> </html> JavaScript Form Submission In JavaScript, you can submit the form using the ”submit” input type and execute a particular function to handle the form data using the onsubmit() event handler. Example In the below code, the form takes users” first and last names. After that, when users click the submit input, it calls the submitForm() function. In the submitForm() function, we used the preventDefault() method to prevent the execution of the function without submitting the form. After that, we use the ”forms” collection to access the form and values of its input fields. At last, we print the input values in the output. <html> <body> <form onsubmit = “submitForm(event)” id = “nameform”> <p><label>First Name: </label><input type = “text” name = “firstname”></p> <p><label>Last Name: </label><input type = “text” name = “lastname”></p> <p><input type = “submit”></p> </form> <div id = “output”> </div> <script> function submitForm(e) { e.preventDefault(); const output = document.getElementById(”output”); const firstname = document.forms[”nameform”][”firstname”].value; const lastname = document.forms[”nameform”][”lastname”].value; output.innerHTML = “First Name: ” + firstname + “, Last Name: ” + lastname; } </script> </body> </html> JavaScript Form Validation In JavaScript, you can also validate the form to ensure the users have filled the required inputs. You can perform the validation check in the function that you are invoking on form submit. Furthermore, you may also show the error message in the output if the form is not fulfilling the particular condition. Example In the below code, we check whether the length of the first name and last name is less than 3 when users submit the form. If the length of firstname or lastname is less than 3, we show the error message. <html> <body> <form onsubmit = “submitForm(event)” id = “nameform”> <p>First Name: <input type = “text” name = “firstname”> </p> <p>Last Name: <input type = “text” name = “lastname”> </p> <p><input type = “submit”></p> </form> <div id = “output”> </div> <script> function submitForm(e) { e.preventDefault(); const output = document.getElementById(”output”); const firstname = document.forms[”nameform”][”firstname”].value; const lastname = document.forms[”nameform”][”lastname”].value; if (firstname.length < 3 || lastname.length < 3) { output.innerHTML += “The length of the first name or last name should be greater than 3. <br>”; } else { output.innerHTML = “First Name: ” + firstname + “, Last Name: ” + lastname; } } </script> </body> </html> JavaScript Form Data Validation It is also required to validate the input data. Sometimes, it happens that you want users to pass the numeric data, but they pass the string data by mistake. In such cases, developers are required to validate the data and show the error message. You may validate the data on the client side or server side. It is a best practice to validate the data on the client side and send pure data to the

JavaScript – DOM Methods

JavaScript – DOM Methods ”; Previous Next In JavaScript, DOM methods are used to perform a particular action on HTML elements. The DOM represents a HTML document or web page with a logical tree. In the tree, each branch ends in a node, and each node contains objects. DOM methods allow us programmatic access to the tree. Using the DOM methods, you can change the document”s structure, style, or content. For example, you can use DOM methods to access HTML elements using id, attribute, tag name, class name, etc., add events to the document or HTML elements, add new HTML elements to the DOM, etc. Syntax Following is the syntax to access and execute the DOM method in JavaScript − window.document.methodName(); OR document.methodName(); You may or may not use the ”window” object to access the document object”s method. Here, we have explained some HTML DOM methods with examples and covered other methods in the reference. JavaScript document.getElementById() Method The JavaScript getElementById() method of the document object is the most popular method to access the HTML elements using the id. Syntax Follow the syntax below to use the document.getElementById() method. const ele = document.getElementById(“id”); The getElementById() method takes an id of the HTML element as a parameter. Example In the below code, the id of the ”div” element is ”output”. In JavaScript, we use the document.getElementById() method to access the div element using its id. Also, we use the ”innerHTML” property of the element to add extra HTML to the ”div” element. <html> <body> <button onclick = “accessEle()”> Access output and write </button> <p id = “output”> </p> <script> function accessEle() { document.getElementById(“output”).innerHTML = “Hello User! You have just clicked the button!”; } </script> </body> </html> JavaScript document.addEventListener() Method The addEventListener() method is used to add the event to the document. Syntax Follow the syntax below to use the addEventListener() method with a document. document.addEventListener(”mouseover”, function () { // Perform action on the document. }); The addEventListener() method takes the event name as the first parameter and the callback function as a second parameter. Example In the below code, we added the ”mouseover” event to the document. Whenever you hover over the document, it will change the background color of the document body to red. <html> <body> <h3>JavaScript – document.addEventListener() Method </h3> <p> Hover over here to change background color </p> <script> document.addEventListener(”mouseover”, function () { document.body.style.backgroundColor = ”red”; }); </script> </body> </html> JavaScript document.write() Method The document.write() method adds the text or HTML to the document. It replaces the content of the document with the HTML passed as an argument of the method. Syntax Follow the syntax below to use the document.write() method. document.write(HTML) You can replace the ”HTML” argument with the text or HTML. Example In the below code, we execute the writeText() function when you click the button. In the function, we use the document.write() method to add HTML to the web page. It replaces the HTML of the whole web page. <html> <body> <button onclick = “writeText()”> Add HTML </button> <script> function writeText() { document.write(“<p>Hello Users, Text is written using the document.write() method. </p>”); } </script> </body> </html> List of DOM Methods In the below table, we have listed all methods related to the HTML DOM. You can access all methods using the ”document” object. Method Description addEventListener() It is used to add an event listener to the document. adoptNode() It is used to adopt the node from the other documents. append() It appends the new node or HTML after the last child node of the document. caretPositionFromPoint() It returns the caretPosition object, containing the DOM node based on the coordinates passed as an argument. close() It closes the output stream opened using the document.open() method. createAttribute() It creates a new attribute node. createAttributeNS() It creates a new attribute node with the particular namespace URI. createComment() It creates a new comment node with a specific text message. createDocumentFragment() It creates a DocumentFragment node. createElement() It creates a new element node to insert into the web page. createElementNS() It is used to create a new element node with a particular namespace URI. createEvent() It creates a new event node. createTextNode() It creates a new text node. elementFromPoint() It accesses the element from the specified coordinates. elementsFromPoint() It returns the array of elements that are at the specified coordinates. getAnimations() It returns the array of all animations applied on the document. getElementById() It accesses the HTML element using the id. getElementsByClassName() It accesses the HTML element using the class name. getElementsByName() It accesses the HTML element using the name. getElementsByTagName() It accesses the HTML element using the tag name. hasFocus() It returns the boolean value based on whether any element or document itself is in the focus. importNode() It is used to import the node from another document. normalize() It removes the text nodes, which are empty, and joins other nodes. open() It is used to open a new output stream. prepand() It is used to insert the particular node before all nodes. querySelector() It is used to select the first element that matches the css selector passed as an argument. querySelectorAll() It returns the nodelist of the HTML elements, which matches the multiple CSS selectors. removeEventListener() It is used to remove the event listener from the document. replaceChildren() It replaces the children nodes of the document. write() It is used to write text, HTML, etc., into the document. writeln() It is similar to the write() method but writes each statement in the new line. Print Page Previous Next Advertisements ”;

JavaScript – Changing CSS

JavaScript – Changing CSS ”; Previous Next Changing CSS with JavaScript JavaScript allows you to change the CSS of the HTML element dynamically. When HTML gets loaded in the browser, it creates a DOM tree. The DOM tree contains each HTML element in the object format. Furthermore, each HTML element object contains the ”style” object as a property. Here, a ”style” object contains various properties like color, backgroundcolor, etc., to change or get the element”s style. So, you can use various properties of the ”style” object to change the style of the particular HTML element. Syntax Follow the syntax below to change the CSS of the HTML element. element.style.property = value; In the above syntax, ”element” is an HTML element, which you need to access from the DOM tree. The ”property” is a CSS property, and the ”value” can be static or dynamic. Example: Changing the style of the HTML element We have applied the initial style to the div element in the code below. In JavaScript, we change the div element”s background color using the style object”s ”backgroundColor” property. <!DOCTYPE html> <html> <head> <style> div { background-color: blue; width: 700px; height: 100px; color: white; } </style> </head> <body> <div id = “square”> Changing the color of this Div. </div> <br> <button onclick=”changeColor()”> Change Color </button> <script> function changeColor() { let square = document.getElementById(”square”); square.style.backgroundColor = ”red”; } </script> </body> </html> Example: Adding multiple styles to a single HTML element In the below code, we change multiple CSS properties of the <div> element in the changeStyle() function. We use the ”backgroundColor’, ”color’, ”fontSize’, and ”width” properties to change the CSS. <!DOCTYPE html> <html> <body> <div id = “square”> Changing the style of this Div. </div> <br> <button onclick = “changeStyle()”> Change color </button> <script> function changeStyle() { document.getElementById(”square”).style.backgroundColor = ”red”; document.getElementById(”square”).style.color = “white”; document.getElementById(”square”).style.fontSize = “25px”; document.getElementById(”square”).style.width = “700px”; } </script> </body> </html> Changing Style of the Element When Event Triggers You can also change the style of the element when a particular event triggers. Example In the below code, we added the ”click” event to the <div> element. When users click the button, it changes the background color of the div element. <!DOCTYPE html> <html> <head> <style> div { width: 700px; height: 100px; color: white; background-color: orange; } </style> </head> <body> <div id = “square”> Click Me </div> <br> <script> const square = document.getElementById(”square”); square.addEventListener(”click”, () => { square.style.backgroundColor = ”green”; square.style.fontSize = “25px”; }); </script> </body> </html> Example In the below code, we added the ”hover” event on the div element. When the mouse cursor enters and leaves the div element, it changes the style of the div element. <!DOCTYPE html> <html> <head> <style> div { width: 700px; height: 100px; color: white; background-color: orange; } </style> </head> <body> <div id = “square”> Hover Me </div> <br> <script> const square = document.getElementById(”square”); square.addEventListener(”mouseenter”, () => { square.style.backgroundColor = ”green”; square.style.fontSize = “25px”; }); square.addEventListener(”mouseleave”, () => { square.style.backgroundColor = ”orange”; square.style.fontSize = “initial”; }); </script> </body> </html> Changing CSS of HTML elements Dynamically You can also change the CSS of the HTML element dynamically. You can assign values using the variables. Example We have added the default style to the <div> element in the code below. Also, we have created multiple radio buttons. When users select any radio button, it changes the style of the div element accordingly. <!DOCTYPE html> <html> <head> <style> p { width: 700px; height: 100px; color: white; background-color: blue; } </style> </head> <body> <div><p id = “square”>Select any of the following colors to change the background color</p></div> <div>Yellow: <input type = “radio” id = “yellow” name = “color”></div> <div>Green: <input type = “radio” id = “green” name = “color”></div> <div>Red: <input type = “radio” id = “red” name = “color”></div> <script> let square = document.getElementById(”square”); // Changing the style when radio button changes let colors = document.getElementsByName(”color”); for (let i = 0; i < colors.length; i++) { colors[i].addEventListener(”change”, function () { square.style.backgroundColor = this.id; }); } </script> </body> </html> Print Page Previous Next Advertisements ”;

JavaScript – Event Bubbling

JavaScript – Event Bubbling ”; Previous Next Event Bubbling Event bubbling is a concept in JavaScript that refers to the order in which events are handled as they propagate through the DOM (Document Object Model) hierarchy. When an event occurs on a particular element, such as a click or a keypress, it can trigger handlers not only on that specific element but also on its ancestors in the DOM tree. Event Bubbling Steps Here”s a step-by-step explanation of event bubbling − Event Triggering An event is triggered on a specific DOM element, like a button being clicked or a key being pressed. This is the starting point of the event propagation. Capturing Phase (optional) The event can optionally go through the capturing phase. This phase starts from the root of the DOM tree and moves towards the target element. During this phase, event handlers registered with the addEventListener method using the third parameter true will be executed. Target Phase The event reaches the target element, the one on which the event originally occurred. Bubbling Phase After the target phase, the event starts to bubble up from the target element towards the root of the DOM tree. During this phase, event handlers registered without the third parameter or with the third parameter set to false will be executed. Event Bubbling using 2 Nested DIVs In this example of nested <div> elements, event bubbling is evident as the click event on the child <div> propagates up through the DOM hierarchy to trigger the click event listener on the parent <div>. Despite being clicked on the child, both the child and parent event listeners respond to the click event sequentially. This behaviour showcases the default event bubbling mechanism in the DOM, where events traverse from the target element up to its ancestors, allowing multiple elements to respond to the same event. In the console, upon clicking the child <div>, the log messages for both the child and parent event listeners are displayed, illustrating the event bubbling process. <!DOCTYPE html> <html lang=”en”> <head> <style> .parent { width: 600px; height: 200px; background-color: #eee; position: relative; cursor: pointer; } .child { width: 400px; height: 100px; background-color: #66c2ff; position: absolute; top: 50px; left: 50px; } #message { margin-top: 10px; font-weight: bold; } </style> </head> <body> <h2>Nested Divs</h2> <div class=”parent” id=”parentDiv”> <div class=”child” id=”childDiv”>Click me!</div> </div> <div id=”message”></div> <script> let messageElement = document.getElementById(”message”); document.getElementById(”parentDiv”).addEventListener(”click”, function () { messageElement.innerHTML+=”Parent div clicked<br>”; }); document.getElementById(”childDiv”).addEventListener(”click”, function () { messageElement.innerHTML+=”Child div clicked<br>”; }); </script> </body> </html> The grey box is the parent div and blue box is the child div. Event Bubbling using 3 Nested Levels In this example with three nested levels of <div> elements, event bubbling is demonstrated as a click on the innermost Level 3 <div> triggers successive click event listeners on the parent Level 2 and Level 1 <div> elements. Styled with distinctive background colours, each level visually represents its hierarchy. Upon clicking the Level 3 <div>, the event propagates up, invoking event listeners for higher-level elements. Console logs reveal messages indicating the clicked level and its background colour, showcasing the streamlined event bubbling mechanism for handling nested structures in the DOM. <!DOCTYPE html> <html> <head> <style> .level1 { background-color: #ff9999; padding: 20px; text-align: center; max-width: 80%; cursor: pointer; } .level2 { background-color: #99ff99; padding: 15px; } .level3 { background-color: #9999ff; padding: 10px; cursor: pointer; } #message { margin-top: 10px; font-weight: lighter; border: 1px solid #ddd; padding: 10px; max-width: 80%; background-color: #f9f9f9; border-radius: 5px; font-family: ”Arial”, sans-serif; font-size: 14px; color: #333; } </style> </head> <body> <div class=”level1″ id=”div1″> Level 1 <div class=”level2″ id=”div2″> Level 2 <div class=”level3″ id=”div3″> Level 3 (Click me!) </div> </div> </div> <div id=”message”></div> <script> const messageElement = document.getElementById(“message”); document.getElementById(”div1”).addEventListener(“click”, function (event) { messageElement.innerHTML += “Clicked on Level 1, Background Color:” + getComputedStyle(event.target).backgroundColor + “<br>”; }); document.getElementById(”div2”).addEventListener(“click”, function (event) { messageElement.innerHTML += “Clicked on Level 2, Background Color:” + getComputedStyle(event.target).backgroundColor + “<br>”; }); document.getElementById(”div3”).addEventListener(”click”, function (event) { messageElement.innerHTML +=”Clicked on Level 3, Background Color:” + getComputedStyle(event.target).backgroundColor + “<br>”; }); </script> </body> </html> Print Page Previous Next Advertisements ”;

JavaScript – DOM Document

JavaScript – DOM Document ”; Previous Next HTML DOM Document The HTML DOM document object owns all objects in the webpage. It represents the webpage. When the webpage is loaded in the web browser, it creates an HTML DOM ”document” object. It is the root of the HTML document. The DOM document object contains the various properties and methods you can use to get details about HTML elements and customize them. With document objects, JavaScript can access, and change document”s structure, content or style. To access any HTML element, you should always start accessing with the DOM document object. Accessing DOM Document Object The webpage is represented as the DOM document object. If we want to access any element in the webpage, we need to first start accessing the document object. In JavaScript, the document object is a property of the window object. So we can access the document object as a property of window object using window.document syntax. We can also access it without writing window. window.document or simply document The DOM Document Properties The HTML DOM document object provides us with many properties that can be used to access and manipulate the HTML elements. Here, we have listed all properties of the document object. Property Description activeElement To get the currently focused element in the HTML document. adoptedStyleSheets It sets the array of the newly constructed stylesheets to the document. baseURI To get the absolute base URI of the document. body To set or get the document”s <body> tag. characterSet To get the character encoding for the document. childElementCount To get a count of the number of child elements of the document. children To get all children of the document. compatMode To get a boolean value representing whether the document is rendered in the standard modes. contentType It returns the MIME type of the document. cookie To get the cookies related to the document. currentScript It returns the script of the document whose code is currently executing. defaultView To get the window object associated with the document. designMode To change the editability of the document. dir To get the direction of the text of the document. doctype To get the document type declaration. documentElement To get the <html> element. documentURI To set or get the location of the document. embeds To get all embedded (<embed>) elements of the document. firstElementChild To get the first child element of the document. forms It returns an array of <form> elements of the document. fullScreenElement To get the element that is being presented in the full screen. fullScreenEnabled It returns the boolean value, indicating whether the full screen is enabled in the document. head It returns the <head> tag of the document. hidden It returns a boolean value, representing whether the document is considered hidden. images It returns the collection of the <img> elements. lastElementChild It returns the last child element of the document. lastModified To get the last modified date and time of the document. links To get the collection of all <a> and <area> elements. location To get the location of the document. readyState To get the current state of the document. referrer To get the URL of the document, which has opened the current document. scripts To get the collection of all <script> elements in the document. scrollingElement To get the reference to the element which scrolls the document. styleSheets It returns the style sheet list of the CSSStyleSheet object. timeLine It represents the default timeline of the document. title To set or get the title of the document. URL To get the full URL of the HTML document. visibilityState It returns the boolean value, representing the visibility status of the document. Here, we have explained some properties of the HTML DOM ”document” object with examples in JavaScript. Document childElementCount Property In JavaScript, the childElementCount property of the document object returns the count of the child elements of the document. Syntax Follow the syntax below to use the childElementCount property of document object in JavaScript. document.childElementCount; Example In the below code, the childElementCount property returns 1, as the document contains only 1 child element, . Other HTML elements are the child of the body. <html> <body> <div>First Element</div> <div>Second Element</div> <div>Third Element</div> <div id = “output”> </div> <script> document.getElementById(”output”).innerHTML = “Total number of child elements in the document is: ” + document.childElementCount; </script> </body> </html> Output First Element Second Element Third Element Total number of child elements in the document is: 1 Document Links Property The Document Links property returns the collection of all links of the document. After that, you can use the for…of loop to traverse the collection of links. Syntax Follow the syntax below to use the document ”links” property in JavaScript. document.links; Example In the below code, the web page contains the two <a> elements. We access their href attribute”s value using the links property. After that, we used the for…of loop to traverse the collection of links and print them on the web page. <html> <body> <div> <a href = “https://tutorialspoint.com/”> Home </a> </div> <div> <a href = “https://www.tutorialspoint.com/articles/category/javascript”> JavaScript </a> </div> <div id = “output”> </div> <script> const allLinks = document.links; document.getElementById(“output”).innerHTML += “The webpage contains the below links. <br>”; for (let link of allLinks) { output.innerHTML += link + “<br>”; } </script> </body> </html> Output Home JavaScript The webpage contains the below links. https://tutorialspoint.com/ https://www.tutorialspoint.com/articles/category/javascript Document Title Property In JavaScript, the DOM document title property returns the title of the web page. Syntax Follow the syntax below to access the DOM document title of the web page. document.title; Example In the below code, we have added the <title> tag in the <head> tag. After that, we used the ”title” property of the document to access the web page”s title. <html> <head> <title> JavaScript – HTML DOM Document </title> </head> <body> <div id = “output”>The title of the document is: </div> <script> document.getElementById(“output”).innerHTML += document.title; </script> </body> </html> Output The title of the document is: JavaScript – HTML DOM

JavaScript – Extending Errors

JavaScript – Extending Errors ”; Previous Next The custom errors in JavaScript are errors that you create yourself, as opposed to the built-in errors that JavaScript throws. You can create custom errors to handle specific types of errors that may occur in your code. To create a custom error, you can use the Error constructor. The Error constructor takes a string as its argument, which will be the message of the error. Extending the Error Class: Creating Custom Errors The best way to create custom errors is by creating a new class and extending it using the ”extends” keyword. It uses the concept of inheritance, and the custom error class inherits the properties of the Error class. In the constructor() function, you can initialize the properties of the custom error class. Syntax You can follow the syntax below to create custom errors by extending the Error class. class customError extends Error { constructor(message) { super(message) // Initialize properties } } In the above code, we call the parent class constructor using the super() method. You can also initialize the properties of the customError class in the constructor function. Example In the code below, we take the input from the user. When a user clicks the check age button, it calls the checkAge() function. We have defined the ageError class in JavaScript code and extended it with the Error class. In the ageError class, we have added the constructor() function to initialize the properties. In the constructor() function, we used the super() method to initialize the message property of the Error class. Also, we have initialized the ”name” and ”age” properties in the constructor function. In the checkAge() function, we throw the error if the age is less than 18, and in the catch{} block, we print the error message and age. <html> <body> <p>Enter your age: <input type = “number” id = “age” /> </p> <button onclick = “checkAge()”> Check Age </button> <p id = “demo”> </p> <script> const output = document.getElementById(“demo”); class ageError extends Error { constructor(message, age) { super(message); this.name = “ageError”; this.age = age // Custom property } } function checkAge() { const ageValue = document.getElementById(”age”).value; try { if (ageValue < 18) { // Throw error when age is less than 18 throw new ageError(“You are too young”, ageValue); } else { output.innerHTML = “You are old enough”; } } catch (e) { output.innerHTML = “Error: ” + e.message + “. <br>”; output.innerHTML += “Age: ” + e.age + “<br>”; } } </script> </body> </html> Output Enter your age: 5 Check Age Error: You are too young. Age: 5 If you want to create multiple new classes for the custom errors only to provide the clarified error type and message and don”t want to change the properties of the Error class, you can use the syntax below. class InputError extends Error {}; Let”s learn it via the example below. Example In the code below, we have created 3 different custom classes and extended them with the Error class to create custom errors. In the try{} block, we throw the StringError. In the catch{} block, we used the instanceOf operator to check the type of the error object and print the error message accordingly. <html> <body> <div id = “demo”> </div> <script> const output = document.getElementById(“demo”); class StringError extends Error { }; class NumberError extends Error { }; class BooleanError extends Error { }; try { throw new StringError(“This is a string error”); } catch (e) { if (e instanceof StringError) { output.innerHTML = “String Error”; } else if (e instanceof NumberError) { output.innerHTML = “Number Error”; } else if (e instanceof BooleanError) { output.innerHTML = “Boolean Error”; } else { output.innerHTML = “Unknown Error”; } } </script> </body> </html> Output String Error Multilevel Inheritance You can create a general custom error by extending it with the Error class. After that, you can extend the custom error class to create a more generalized error class. Let”s understand it via the example below. Example In the code below, we have defined the ”NotFound” class and extended it using the Error class. After that, we defined the ”propertyNotFound” and ”valueNotFound” classes and extended them with the ”NotFound” class. Here, we have done the multilevel inheritance. In the try block, we throw a valueNotFound error if the array doesn”t contain 6. In the catch block, we print the error. <html> <body> <div id = “output”> </div> <script> const output = document.getElementById(“output”); class NotFound extends Error { constructor(message) { super(message); this.name = “NotFound”; } } // Further Inheritance class propertyNotFound extends NotFound { constructor(message) { super(message); this.name = “propertyNotFound”; } } // Further Inheritance class ElementNotFound extends NotFound { constructor(message) { super(message); this.name = “ElementNotFound”; } } try { let arr = [1, 2, 3, 4, 5]; // Throw an error if array doesn”t contain 6 if (!arr.includes(6)) { throw new propertyNotFound(“Array doesn”t contain 6″); } } catch (e) { output.innerHTML = e.name + “: ” + e.message; } </script> </body> </html> Output propertyNotFound: Array doesn”t contain 6 You can also throw the propertyNotFound error if any object doesn”t contain the particular property. Print Page Previous Next Advertisements ”;

JavaScript – Performance

JavaScript – Performance ”; Previous Next JavaScript is very important in every website today. If JavaScript fails, our website wouldn”t work properly. It is important to focus on the performance on JavaScript as it has impacts on delivering a positive user experience, retaining engagement, and ensuring business success. An optimized JavaScript would ensure the pages load faster and responsive interactions contribute to users satisfaction and hence higher conversion rates as well as higher search engine rankings (as the SEO would be better). In a competitive digital landscape, optimized JavaScript code not only attracts and retains users but also enhances resource efficiency, reducing server costs and providing a competitive advantage. With the increasing prevalence of mobile devices and the emphasis on Progressive Web Apps, performance optimization is not only a user expectation but a strategic necessity for businesses aiming to stand out and thrive in the online space. Optimizing DOM Manipulation DOM manipulation is where each element is represented as a node in the tree and accessed or modified via their ids, class names etc. These DOM manipulation operations should be minimized as much as possible and would have a significant impact on the speed of our application. Let us consider the below example where we are dynamically creating a list of 1000 items. Example Naive Code <!DOCTYPE html> <html> <body> <ul id=”itemList”></ul> <script> const itemList = document.getElementById(”itemList”); // Inefficient DOM manipulation for (let i = 0; i < 1000; i++) { itemList.innerHTML += `<li>Item ${i}</li>`; } </script> </body> </html> Optimized Code <!DOCTYPE html> <html> <body> <ul id=”itemList”></ul> <script> // Efficient DOM manipulation using document fragment const itemList = document.getElementById(”itemList”); const fragment = document.createDocumentFragment(); for (let i = 0; i < 1000; i++) { const listItem = document.createElement(”li”); listItem.textContent = `Item ${i}`; fragment.appendChild(listItem); } itemList.appendChild(fragment); </script> </body> </html> Asynchronous Operations with Promises To prevent the main thread from blocking, we must prioritize asynchronous programming. Consider this example: data retrieval from an API using Promises; in such instances, a Promise proves indispensable for managing asynchronous data fetching. Preventing the UI from freezing during operation; enhancing the overall user experience: these are the benefits. Example <!DOCTYPE html> <html> <body> <h2>Asynchronous Operations with Promises</h1> <div id=”dataContainer”></div> <script> // Fetch data asynchronously function fetchData() { return new Promise((resolve, reject) => { // Simulating an API call with a delay setTimeout(() => { const data = { message: ”Hello, world!” }; resolve(data); }, 1000); }); } // Usage of the fetchData function fetchData() .then(data => { document.getElementById(”dataContainer”).textContent = data.message; }) .catch(error => { alert(”Error fetching data:”, error); }); </script> </body> </html> Deferred JavaScript Loading JavaScript is normally loaded when the page is opened, however by delaying the loading of JavaScript we can optimize page load performance especially when dealing with non-essential scripts. When browsers come across the <script> tag, they normally block the rendering until the script has finished downloading and executing. However, by using the defer attribute in the script tag, we can instruct the browser to continue downloading the script in the background while it continues to parse & render the HTML. The script is then executed after the HTML is completely parsed. Example <!DOCTYPE html> <html> <body> <p>Deferred JavaScript Loading</p> <script defer src=”https://code.jquery.com/jquery-3.6.4.min.js”></script> <div id=”loadingMessage”>JavaScript is loading…</div> <script> // Add an event listener to indicate when the JavaScript is fully loaded document.addEventListener(”DOMContentLoaded”, function() { document.getElementById(”loadingMessage”).textContent = ”JavaScript has finished loading!”; }); </script> </body> </html> Another option to the above code is to use the async attribute. While similar to defer, async loads the script asynchronously, but it doesn”t guarantee the order of execution. The script that finishes loading first will be executed first. Avoiding Global Variables Global variables are those which are visible throughout the code, or have a big scope. It is import to understand if our code actually requires the scope of variables to be global or can it be managed efficiently by code encapsulation. The below examples demonstrates the usage of encapsulation to avoid global variables hence leading to better performance of the script. Example <!DOCTYPE html> <html> <body> <h2>Avoiding Global Variables</h2> <div id=”result”></div> <script> var resultElement = document.getElementById(”result”); // Inefficient use of global variables var globalVar = 10; function addNumbers(x, y) { return globalVar + x + y; } resultElement.innerHTML += “Using global variable, the sum is ” + addNumbers(51, 7) + “<br>”; // Improved encapsulation (function () { var localVar = 10; function addNumbers(x, y) { return localVar + x + y; } resultElement.innerHTML += “Using encapsulation, the sum is ” + addNumbers(51, 7); })(); </script> </body> </html> While we have discussed performance optimization in this tutorial from a JavaScript point of view, it is important to note that certain optimizations remain constant irrespective of the language. This includes scenarios like using switch case instead of length if else if, memory management, concurrency, etc. The performance optimization of JavaScript has impacts across industries & applications. In ecommerce, a high speed page load has proven to enhance user engagement and boost conversation rates, while in social media JavaScript has helped in providing seamless interactions. News and media related websites benefit as the content gets updated quickly and only learning platforms (edtech industry) requires JavaScript for interactive educational components. On the other hand, financial applications, collaboration tools, gaming websites, and healthcare apps all demand optimized JavaScript to ensure their interfaces are responsive and process data in a timely manner. Print Page Previous Next Advertisements ”;

JavaScript – Keyboard Events

JavaScript – Keyboard Events ”; Previous Next The keyboard events in JavaScript provide a way to interact with a web page or application based on the user”s keyboard input. These events allow developers to capture and respond to various keyboard actions, such as key presses, key releases, and character inputs. The primary keyboard events in JavaScript include keydown, keypress, and keyup. Common Keyboard Events Keydown Event − When a key on the keyboard is pressed down, it triggers the keydown event. This event equips developers with information about the specific key that was pressed: this includes its code and an indicator of whether certain modifier keys such as Shift, Ctrl, or Alt were also depressed. Keypress Event − The keypress event triggers when a user types an actual character. Non-character keys, such as Shift or Ctrl, do not activate this event. Developers frequently utilize it to capture user input for form fields or create interactive typing features. Keyup Event − Upon the release of a previously pressed key, the system initiates the firing of a keyup event; this particular event proves beneficial in tracking specific keys” releases and subsequently implementing actions, thereby creating an interactive user experience. Keyboard Event Properties For keyboard events in JavaScript, several properties are commonly used to gather information about the key pressed. Here are some key properties specifically relevant to keyboard events − Property Description event.key String representing the key value of the pressed key. event.code String representing the physical key on the keyboard. event.location Integer indicating the location of the key on the keyboard. event.ctrlKey Boolean indicating whether the Ctrl key was held down. event.shiftKey Boolean indicating whether the Shift key was held down. event.altKey Boolean indicating whether the Alt key was held down. event.metaKey Boolean indicating whether the Meta (Command) key was held down. event.repeat Boolean indicating whether the key event is a repeat event. event.isComposing Boolean indicating whether the event is part of a composition of multiple keystrokes. event.which Deprecated property; previously used to identify the numeric key code. event.getModifierState(keyArg) Method that returns a boolean indicating whether the modifier key is pressed. Example: Keydown Event This example illustrates the application of JavaScript”s keydown event. The event listener seizes the keydown event upon pressing any key, displaying in an HTML element identified as “output” – its corresponding key (an event property). <!DOCTYPE html> <html> <body> <h3>Press any key</h3> <script> document.addEventListener(”keydown”, function (event) { document.getElementById(”output”).innerHTML = “Key pressed: ” + event.key; }); </script> <div id=”output”></div> </body> </html> Example: Keypress Event In this example, the keypress event is utilized to capture a typed character. When a character is typed, the event listener triggers, and the character is displayed in the HTML element with the id “output”. <!DOCTYPE html> <html> <body> <h3>Type a character</h3> <div id=”output”></div> <script> document.addEventListener(”keypress”, function (event) { document.getElementById(”output”).innerHTML = “Character pressed: ” + event.key; }); </script> </body> </html> Example: Keyup Event The keyup event is showcased in this example. It captures the event when a key is released after being pressed. The released key is then displayed on screen. <!DOCTYPE html> <html> <body> <h3>Press and Release a key</h3> <div id=”output”></div> <script> document.addEventListener(”keyup”, function (event) { document.getElementById(”output”).innerHTML = “Key released: ” + event.key; }); </script> </body> </html> There is a difference between keydown and keypress. keydown is triggered when any key is pressed down, providing information about the pressed key, including modifiers. keypress is triggered specifically when a character key is pressed, providing information about the typed character without details on modifiers. Keydown fires continuously as long as the key is held down. In all the above examples, we have used the addEventListener but these events can be listened to without this function as well. This is because of you can assign event handlers directly to specific properties. However, keep in mind that using addEventListener is generally considered a better practice because it allows you to attach multiple event handlers to the same event, and it separates JavaScript logic from the HTML structure. Example: Without using addEventListener method In this example, we have an input box. When it detects a keydown event (onkeydown), the handleKeyDown function is called and when it detects a keyup event (onkeyup) it calls the handleKeyUp function. Both the functions print appropriate messages to the screen. <!DOCTYPE html> <html> <body> <div>Enter some text: <input onkeydown=”handleKeyDown(event)” onkeyup=”handleKeyUp(event)”> </div> <div id=”output”></div> <script> function handleKeyDown(event) { document.getElementById(”output”).innerHTML+= “Key pressed: ” + event.key+”<br>Key code: ” + event.keyCode+”<br>”; } function handleKeyUp(event) { document.getElementById(”output”).innerHTML+= “Key released: ” + event.key+”<br><br>”; } </script> </body> </html> Print Page Previous Next Advertisements ”;