Events, Arrow functions, and DOM manipulation in JavaScript
“Objects are passed around by reference. They are never copied:” ― Douglas Crockford
DOM (Document object model) :
Throughout the previous Javascript blogs, you all have learned the efficient usage of variables, loops, arrays, and functions. A big pat on your back! Now begins the fun part, adding functionalities and responsiveness to your static website!
We can’t add functions or events to the entire Web page, we must choose our elements. To do so, we must learn a very important concept called the DOM.
DOM stands for “Document Object Model”. By default, the entire HTML file is seen as a document and all its elements are perceived as objects. This is stored in a hierarchical pattern as shown in the figure.
Example of HTML being stored as a Document:
HTML:
Now we can’t add functionalities or responsiveness to the entire document. We must choose our element. To do so DOM offers simple methods which are explained below.
To pick a HTML element using its tag:
document.getElementsByTagName(“Tag_name ex: input”).
To pick a HTML element using its class:
document.getElementsByClassName(“Class_name ex: Navigation”).
To pick a HTML element using its ID:
document.getElementById(“ID_name ex: First”).
As you must have noticed, ID has Element but both Tag and Class have elements in the method. This is because the getElementsByTagName and getElementsByClassName give the output in an array format whereas ID gives a single element. After all, ID has to be unique. Hence if there are 5 buttons, we can access the third document.getElementsByTagName(“Button”)[2]. (Remember array index starts with 0).
We can also use a special method that can incorporate all classes, Id’s and Tags.
document.querySelector(“ ”)
For Tags: Specify the Tag Name.
For Class: Specify .ClassName
For ID: Specify #IdName
Note: It is similar to CSS. Hence we can also specify elements inside elements similar to CSS. If there are multiple instances of the same element, querySelector chooses the 1st.
To process all elements of the same Tag/Class, use querySelectorAll().
Now that the HTML element is chosen, we can store it in a variable.
Ex: const name = document.getElementById(“ID_name ex: First”).
After storing the elements, let’s discuss the HTML properties that we can access using further DOM methods. These include getting the HTML content inside an element, its text, its styles, and so on.
DOM Methods.
element.innerHTML(“ ”) : Can access and therefore change the HTML syntax of the element.
Example: document.getElementsByClassName(“hello”)[0].innerHTML(“<p>Hello</p>”);
element.createElement(“”): Can create a new HTML element.
Example: document.createElement(“ol”);
element.textContent: Can also access the text associated to the HTML element.
Example: var text = document.getElementsByTagName(“li”)[4].textContent;
element.getAttribute(“ ”): Get access the attribute specified in the quotation marks.
Example: document.querySelector(“.abc”).getAttribute(“src”);
element.setAttribute(“ attribute_name”,” New_value”): Can also change the attribute value in one function.
Example: document.querySelector(“.abc”).setAttribute(“src”,” https://www.youtube.com/”);
element.classList : This method will return all the classes associated with the element. We can also add a class using .classList.add(“class_name”), remove a class using .classList(“class_name”).
Another intuitive method to add a class if absent and remove the class when present can be done by .classList.toggle(“class_name”);
Changing the Style of an element.
Let’s say we want to change the background color of the element.
Element.style.backgroundColor = “color”;
Note: The CSS properties are written in the Camel case in Javascript. (font-size in CSS becomes font size)
Before this statement, the color of the list is Black but it changes as the Javascript colors it red.
Forms
Javascript contains special keywords and methods reserved for forms. They can be used to select between various forms, their attributes, and their validations as well.
document.forms[0] : This selects the first form in the document.
document.forms.length: To find the number of forms in the document.
Form Validations:
Ever tried to submit a form without ticking on the terms and conditions? You get an error, right? This happens because the form input accepts data and simultaneously checks if it matches the required conditions. This is very important to make sure that the user fills each input correctly.
Validity: It contains various objects which check specific validity issues of the data that include:
· too long: It returns true if the length of the text is more than the maximum specified max-length attribute
· too short: It returns true if the length of the text is less than the minimum specified min-length attribute
· type mismatch: When the type attribute is email etc, this object checks if the format is correct or not. It returns true in the case of the wrong format.
We can also customize a validity breach message in case of wrong input:
setCustomValidity(“message”)
Example:
Hence the output looks like this:
Just note that in this example when the user enters a text in the input, its validity is checked and in case of a mismatch, the error message will be delivered. Dealing with such events will come later in this blog.
With the use of the above methods, we can get all properties of an HTML element. By using functions and conditions, these properties can be altered.
Events:
An event is an action that occurs when a browser or the user reacts to the live website. For example: Click on a button. Till now, we have been making static buttons, that cannot be responded to. In this section, we shall look at ways to give a respond to occurring events.
Some more examples of Website events:
· Hovering over an element
· Scrolling
· Clicking an element
· Submitting a form
· Getting keyboard input from the user
· Etc
Firstly we need to select the element on which the event is going to occur. It could be a button, an image, div, etc.
To add an event to the element we attach an event Listener which listens for any particular action done by the browser or the user.
Syntax: element.addEventListner(event,function);
Note: The function is called without the brackets, only the name of the function should be given.
Some important events include:
· Click: When the user clicks on the element
· Dbclick: When the user double clicks on the element
· Focus: When the element is in focus
· Keypress: When the user presses a key on the keyboard
· Submit: When a form is submitted
· Mouseover: When the mouse is brought on the element or its children
· Mouseout: When a user moves the mouse out of an element, or out of one of its children
· Play: When a media is has been started and no longer paused
· Input: When a text is entered into an input tag
The function parameter takes a function event which will be called if the event occurs.
Example:
HTML:
<button class=”Rectangle1">
Click ME!
</button>
JavaScript:
document.querySelector(“.Rectangle1”).addEventListener(“click”,buttonclick);
function buttonclick(){
document.querySelector(“.Rectangle1”).innerHTML=”Clicked”;
}
Hence when a button is clicked:
Event listners can also be removed using .removeEventListner(event,function)
Events can also be handled by HTML attributes forex: onclick=” function”, but they are far less powerful than Javascript EventListners.
Event listners can also be removed using .removeEventListner(event,function)
Events can also be handled by HTML attributes forex: onclick=” function”, but they are far less powerful than Javascript EventListners.
Another exampke of an event Listner:
Javascript:
document.querySelector(“.Rectangle1”).style.backgroundColor=”blue”;
document.querySelector(“.Rectangle1”).addEventListener(“mouseover”,buttonclick);
function buttonclick(){
document.querySelector(“.Rectangle1”).style.backgroundColor=”red”;
}
Remember to also add a mouse out event listener otherwise once the button is hovered into, it will remain in the red.
Arrow functions:
As you must have noticed, for every small event or loop we have to define a function. Forming so many functions and giving them different names is a tall task. By a little trick called arrow functions, we can place functions at their source without giving any names! One can even return a value using this syntax.
Syntax: (a,b) => a + b + 100;
Here the function takes ‘a’ and ‘b’ as parameters and carries out their addition with 100.
The only downside to arrow functions is that they are not applicable for a call, bind, and apply methods.
Example:
document.querySelector(“.Rectangle1”).addEventListener(“mouseover”, () => {
document.querySelector(“.Rectangle1”).style.backgroundColor=”red”;
});
Arrow functions support destructuring within, and default parameters.
Javascript DOM and events are very powerful tools that add life to your static website. With their efficient and timely use, you can create a functional web page.