Sunday, October 4, 2020

JavaScript HTML DOM

The Document Object Model, or DOM for short, is a platform and programming interface for HTML (HyperText Markup Language) and XML (eXtensible Markup Language) documents. It provides a data representation comprising all the objects, depicting the structure and content of the document on the web. Every webpage has its own DOM that represents the page so that programs can alter its structure, look, and content.

In simpler terms, when a browser loads a webpage, it creates a model of that page. This model is the DOM tree and is filed in the browser’s memory. It provides functionality globally to the document, including how to obtain the page details and create new elements in the document. Remember, DOM is neither a part of HTML nor JavaScript; it’s a separate set of rules.

With the HTML DOM, you can use JavaScript to build HTML documents, navigate their hierarchical structure, and add, modify, or delete elements and attributes or their content, and so on. Almost anything found in an HTML document can be accessed, changed, deleted, or added using the JavaScript with the help of HTML DOM.

To understand this more clearly, let's consider the following simple HTML document:

Example

<!DOCTYPE html>
<html>
  <head>
    <title>My Page</title>
  </head>
  <body>
    <div id="div">
      <h1>Mobile OS</h1>
    </div>
      <ul>
        <li>Android</li>
        <li>iOS</li>
      </ul>   
    </body>
</html>

The above HTML document can be represented by the following DOM tree:



Every element, attribute, and text content in the HTML creates its own DOM node in the tree. A DOM tree consists of four main types of nodes:

  1. Document node: This is added at the top of the tree and represents the entire page in the browser. As stated above, it is the starting point in the DOM tree; you need to navigate via the document node to access any other node in your DOM tree.

  2. Element nodes: All the HTML elements like heading tags (<h1> to <h6>) and paragraph tags (<p>) in the page create an element node in the tree. You use these nodes to gain access to the elements’ attributes and text nodes.

  3. Attribute nodes: When the opening tags in the HTML document contains attributes, the tree represents them as attribute nodes. These are not the children of the element nodes but a part of them.

  4. Text nodes: Once you have access to the element node, you can reach the text content within that element, stored inside the text nodes of the DOM tree. These nodes cannot have child nodes. Thus, a text node always creates a new branch in the DOM tree, and no further branches come out of it.


Working with the DOM Tree in JavaScript DOM

To access and modify the DOM tree, you need to follow two steps:

·         Locate the node representing the element you want.

·         Works with the node’s content, child elements, and attributes.

We will discuss the various properties and methods in this tutorial based on the DOM tree given below.

 

Accessing the Elements

DOM Queries are the methods that find elements in the DOM tree. They may return one element or a collection of elements in a NodeList. You can select any element you desire from the NodeList with the help of an index number (starting with 0).

The code mentioned below is the HTML and CSS code, common to all the examples. All you would need to do is add the JavaScript code you want to execute.

Code:

    <html>
    <head>
    <!-- CSS styling -->
    <style type="text/css">
    #page{
    max-width400px;
    margin20px auto 20px auto;
    border3px solid aqua;
    }
    h1h2ul{
    paddingauto;
    }
    p{
    text-aligncenter;
    font-sizelarge;
    font-weightbold;
    }
    </style>
    </head>
    <body>
    <div id="page">
    <h1 id="header">TO DO LIST</h1>
    <ul>
    <h2>Beta-Labs JavaScript Tutorial</h2>
    <li id="one" class="mandatory">Learning the concepts</li>
    <li id="two" class="mandatory">Practicing the codes</li>
    <li id="three">Taking quizzes</li>
    <li id="four">Solving Interview Questions</li>
    </ul>
    <!-- JavaScript code -->
    </div>
    </body>
    </html> 


Methods to Select an Individual Element Node

Following are the methods to select an individual element in the tree:

  • getElementById(‘id’): Uses the unique value of the element’s id attribute. The HTML must have an id attribute for the method to select it.

            For example – getElementById(‘one’) 

  • querySelector(‘css selector’): Uses a CSS selector, returns the first matching element.

            For example – querySelector(‘h1’)


The code below combines these methods to add styling to the webpage.


JavaScript Code:

<script type="text/JavaScript">

 document.getElementById('one').style.color="maroon"//change font color
      
   document.querySelector("h1").style.backgroundColor = "blue"//change background color        

</script>

Output:

 

Methods to Select Multiple Elements (NodeLists)

There are three common ways to select multiple elements in the tree:

  • getElementsByClassName(): Selects all the elements that have a specified value for the class attribute.
            For example – getElementsByClassName(‘mandatory’) 
  • getElementsByTagName(): Selects all the elements that have the specified tag names.
            For example – getElementsByTagName(‘h1’) 

  • querySelectorAll(): Uses a CSS selector, returns all the matching elements.

            For example – querySelectorAll(‘li.mandatory’)


The above methods always return a NodeList, even if the list contains only a single element. This fact is important to remember because you need to use square brackets [ ] if you want to access any element in the NodeList. The following code explains all the methods of returning a NodeList.


JavaScript Code:


<script type="text/JavaScript">

    var list_qs = document.querySelectorAll("li.mandatory"); //NodeList
    
    list_qs[0].style.backgroundColor = "blue"//change background color
    
    var list_cn = document.getElementsByClassName('mandatory'); //NodeList
    
    list_cn[0].style.color="white"//change font color
    
    var list_tn = document.getElementsByTagName('h1'); //NodeList
    
    list_tn[0].style.color="gray"//change font color
    
</script>

 

Output:


 

Get/ update Element Content

For Text only: You can access and update the text in the containing element (and its children) with the help of two properties:

  • textContent

document.getElementById('p').textContent; (accessing)
document.getElementById('p1').textContent = newText; (updating) 

  • innerText
document.getElementById('p').innerText; (accessing)
document.getElementById('p1').innerText = newText; (updating) 


Both these properties replace the entire content of the element, including all the markup present. But you should avoid using innerText since it is not part of any standard. Also, this method slows the speed of content loading on the page.

 

For Text and Markup

The innerHTML property gets the content of the element and returns it as one long string, including the markup it contains. But you should be careful of where you use this property since there are some security risks associated with it.

 

For example

document.getElementById('p').innerHTML; (accessing)
document.getElementById('p1').innerHTML = newText; (updating) 

 

The code below shows the three properties clearly. Run the code on your browser, and see the output on your own. Play with the code, try adding and removing things, and see what happens. This will help you understand how these properties work.

Code:

<html>
<head>
<!-- CSS styling -->
<style type="text/css">
p{
colorblue;
border1px solid aqua;
}
#page{
max-width350px;
margin20px auto 20px auto;
}
</style>
</head>
<body>
<div id = "page">
<h3>Accessing and Updating Element Content</h3>
<p id = "p"><em>Beta-Labs</em> tutorial</p>
<p><em id = "p1"></em></p>
<p><em id = "p2"></em></p>
<p><em id = "p3"></em></p>
<!-- JavaScript Code -->
<script>
document.write("<b>Accessing elements:</b></br>");
var x = document.getElementById('p').textContent;
document.write("textContent: " + x + "</br>");
var y = document.getElementById('p').innerText;
document.write("innerText: " + y + "</br>");
var z = document.getElementById('p').innerHTML;
document.write("innerHTML: " + z + "</br>");
//updating elements
document.getElementById('p1').textContent = "<strong>JavaScript</strong> tutorials";
document.getElementById('p2').innerText = "<strong>JavaScript</strong> quizzes";
document.getElementById('p3').innerHTML = "<strong>JavaScript</strong> interview questions";
</script>
</div>
</body>
</html>

 

Output:

 

Adding/ removing HTML Content

In the above example, we added an HTML <strong> tag in the page with the help of innerHTML property. To remove any text content, all you need to do is store an empty string in the element.

document.getElementById(‘p3’).innerHTML = “ ”; (empty string)

This will remove the text nodes of the containing and its child elements from the HTML content.

DOM Manipulation

Another technique to add/remove HTML content is DOM Manipulation. To add HTML content to your webpage, you need to follow the three steps discussed below:

·         Create a new element using createElement().

·         Give it content by creating a text node using createTextNode() and adding it to the element using the appendChild() method.

·         Add the element to the DOM tree by finding the location and then using appendChild().


To remove an element from the webpage, the steps are as follows:

·         Store the element you want to remove in a variable.

·         Store the parent of that element in another variable.

·         Remove the element from its containing element using the removeChild() method.

Let’s implement these methods with the help of a code. We will use the same HTML and CSS code we discussed at the beginning of this tutorial. All you need to do is change the JavaScript in your program. In this example, we will add a paragraph <p> tag in the page, and remove the <h1> tag from it.


Code:


<script type="text/JavaScript">

    //Adding new element
    var newEl = document.createElement('p'); //create element node
    var newText = document.createTextNode('Node added using DOM manipulation.'); //create text node
    
    newEl.appendChild(newText); //add text node to element node
    var position = document.getElementById("page"); //find the position where you want to add the node
    position.appendChild(newEl); //add element in that position
    
    //Removing an element
    var removeEl = document.getElementById('header'); //store the element you want to remove
    var containerEl = document.getElementById('page'); //find the element which contains the above element
    containerEl.removeChild(removeEl); //remove the element
</script>

Output:


Traversing between Element Nodes

You have the facility to navigate between related element nodes. The techniques available for this purpose include:

·         parentNode: Selects the parent of the current element node (returns a single element).

·         previousSibling/ nextSibling: Selects the previous or next sibling from the tree.

·         firstChild/ lastChild: Selects the first or last child of the current element.






Saturday, October 3, 2020

JavaScript | Events

What is an Event ?

JavaScript's interaction with HTML is handled through events that occur when the user or the browser manipulates a page.

When the page loads, it is called an event. When the user clicks a button, that click too is an event. Other examples include events like pressing any key, closing a window, resizing a window, etc.

Developers can use these events to execute JavaScript coded responses, which cause buttons to close windows, messages to be displayed to users, data to be validated, and virtually any other type of response imaginable.

JavaScript has events to provide a dynamic interface to a webpage. These events are hooked to elements in the Document Object Model (DOM). We can bind events either as inline or in an external script.

When JavaScript code is included in HTML, JS react over these events and allow the execution. This process of reacting over the events is called Event Handling. Thus, js handles the HTML events via Event Handlers.


Some of the HTML events and their event handlers are:

Mouse events:

Event Performed

Event Handler

Description

click

onclick

When mouse click on an element

mouseover

onmouseover

When the cursor of the mouse comes over the element

mouseout

onmouseout

When the cursor of the mouse leaves an element

mousedown

onmousedown

When the mouse button is pressed over the element

mouseup

onmouseup

When the mouse button is released over the element

mousemove

onmousemove

When the mouse movement takes place.


Keyboard events:

Event Performed

Event Handler

Description

Keydown & Keyup

onkeydown & onkeyup

When the user press and then release the key


Form events:

Event Performed

Event Handler

Description

focus

onfocus

When the user focuses on an element

submit

onsubmit

When the user submits the form

blur

onblur

When the focus is away from a form element

change

onchange

When the user modifies or changes the value of a form element


Window/Document events

Event Performed

Event Handler

Description

load

onload

When the browser finishes the loading of the page

unload

onunload

When the visitor leaves the current webpage, the browser unloads it

resize

onresize

When the visitor resizes the window of the browser

Let's discuss some examples of events and their handlers.

 Click Event

See the Pen Click Event by PANKAJ (@pankkap) on CodePen.

 MouseOver Event

See the Pen MouseOver Event by PANKAJ (@pankkap) on CodePen.

 Focus Event

See the Pen Focus Event by PANKAJ (@pankkap) on CodePen.

 Keydown Event

See the Pen Keydown Event by PANKAJ (@pankkap) on CodePen.

 Load Event

See the Pen Load event by PANKAJ (@pankkap) on CodePen.


Ways to Handle Events by Event handlers

There are three ways to assign event handlers.

1) HTML event handler attributes

Event handlers typically have names that begin with on, for example, the event handler for the click event is onclick.

To assign an event handler to an event associated with an HTML element, you can use an HTML attribute with the name of the event handler. For example, to execute some code when a button is clicked, you use the following:

<input type="button" value="Save" onclick="alert('Clicked!')">

In this case, when the button is clicked, the alert box is shown.

 An event handler defined in the HTML can call a function defined in a script. For example:

<input type="button" value="Save" onclick="showAlert()">
<script>
    function showAlert() {
        alert('Clicked!');
    }
</script>

In this example, the button calls the showAlert() function when it is clicked.

The showAlert() is a function defined in a separate <script> element, and could be placed in an external JavaScript file.


2) DOM Level 1 event handlers

Each element has event handler properties such as onclick. To assign an event handler, you set the property to a function as shown in the example:

<input type="button" value="Save" id="button">
 
<script>
let btn = document.querySelector('#btn');
 
btn.onclick = function() {
    alert('Clicked!');
};
</script>

In this case, the anonymous function becomes the method of the button element. Therefore, the this value is equivalent to the element. And you can access the element’s properties inside the event handler:

let btn = document.querySelector('#btn');
 
 btn.onclick = function() {
     alert(this.id); 
 };

Output:

btn


By using the this value inside the event handler, you can access the element’s properties and methods. To remove the event handler, you set the value of the event handler property to null:

btn.onclick = null;

The DOM Level 1 event handlers are still being used widely because of its simplicity and cross-browser support.

3) DOM Level 2 event handlers

DOM Level 2 Event Handlers provide two main methods for dealing with the registering/deregistering event listeners:

·         addEventListener() – register an event handler

·         removeEventListener() – remove an event handler

These methods are available in all DOM nodes.

The addEventListener() method: The addEventListener() method accepts three arguments: an event name, an event handler function, and a Boolean value that instructs the method to call the event handler during the capture phase (true) or during the bubble phase (false). For example:

<input type="button" value="Save" id="button">
 
<script>
let btn = document.querySelector('#btn');

btn.addEventListener('click',function(event) {
    alert(event.type); // click
});
</script>

It is possible to add multiple event handlers to handle a single event, like this:

let btn = document.querySelector('#btn');

btn.addEventListener('click',function(event) {
    alert(event.type); // click
});
 
btn.addEventListener('click',function(event) {
    alert('Clicked!');
});

The removeEventListener() method: The removeEventListener() removes an event listener that was added via the addEventListener(). However, you need to pass the same arguments as were passed to the addEventListener(). For example: 

let btn = document.querySelector('#btn');
 
 // add the event listener
 let showAlert = function() {
     alert('Clicked!');
 };
 btn.addEventListener('click', showAlert);
  
 // remove the event listener
 btn.removeEventListener('click', showAlert);

Using an anonymous event listener as the following will not work:

let btn = document.querySelector("#btn");
btn.addEventListener("click"function () {
  alert("Clicked!");
});

// won't work
btn.removeEventListener("click"function () {
  alert("Clicked!");
});