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!");
});