How to register events in JavaScript?



The interaction between HTML and JavaScript is handled through events. When a user accomplishes some action on the page, an event occurs.

In this tutorial, we will learn how to register events in JavaScript. Let’s move forward to discuss this further.

Using Inline Event Handlers Added as HTML Tag Attributes

Here, we shall learn how this standard event registration works. Adding events to the DOM attribute is a regular practice. But this is a worse approach.

Extending and maintaining the code becomes difficult as HTML and JavaScript come together. Second, if the code loads late when the user interacts with the page elements, they get errors. So we use the assignment method.

We have to use the case-sensitive event names with the prefix “on” in both the HTML attribute and assignment method. That is, onclick, onfocus, and so on.

Users can follow the syntax below for using this approach.

Syntax

<button onclick="doFunction()">
//DOM level 0 event handlers
element.onclick = doAction;
element.onclick = doAction();
element.onclick = function() {}
element.onclick();
element.fireEvent('onclick');

We have both HTML attribute syntax and various assignment syntax in the above.

Example

In this program, we register the event on page load. The function changes its background color when the user clicks on the label or button.

<html> <head> <script> function doAction() { this.style.backgroundColor = "#ffddee"; } function doRegEvent() { idClick.onclick = doAction; idUser.onclick = doAction; } </script> </head> <body onload="doRegEvent();"> <div id="idUser"> Hello, User! </div> <br> <button id="idClick"> Click Me! </button> </body> </html>

Using the addEventListener() Method

Here, we shall learn the working of the addEventListener() method. The event type and the handler are the two parameters of this method. These are DOM level 2 event handlers.

Using this method, we can add event listeners to any HTML DOM object such as an HTML document, HTML element, window object, or xmlHttpRequest object. All browsers support this method except IE8 and prior versions.

We can add many event handlers to one element. We can add the same event to the same element twice. The main advantage of the event handler is that we can access everything with the keyword ‘this' rather than passing values or elements to the function.

Users can follow the syntax below for using this in the program.

Syntax

element.addEventListener(event, function, bubbleCapture); //window
window.addEventListener(event, function() {});

//Passing parameters
element.addEventListener(event, function() {
   functionName(a, b);
});

In the first syntax, we have three parameters which are explained below. The second syntax is to register the event to the browser window. The third syntax represents an anonymous function with parameter usage.

Parameters

  • event − The type of event. For example, click.

  • function − The function that we call when the event occurs.

  • bubbleCapture − A boolean value mentions whether to use event bubbling or event capturing. The default value is false. This is an optional parameter.

Example

We have registered click events in this program using the addEventListener() method. When the user clicks on the button, the current date is displayed to the user.

<html> <head> <title>JavaScript program to register events</title> </head> <body> <h3>Register events using the <i> addEventListener()</i> method</h3> <p>Click the below button</p> <button id="idBtn">Try it</button> <p id="idOut"></p> <script> document.getElementById("idBtn").addEventListener("click", showDate); function showDate() { document.getElementById("idOut").innerHTML = Date(); } </script> </body> </html>

Using the attachEvent() Method

Here, we shall learn the working of the attachEvent() method. The event method is IE-specific and works only in IE8 and below versions.

IE does not support event bubbling. So this method needs only event type and handler arguments. We need to give onclick in attach event syntax to register click event. But for the event listener method, we need to write click to register the click event.

To call registered functions of this method, we need to use the window object. These functions are global.

Users can follow the syntax below for using this method in the program.

Syntax

element.attachEvent (event, functionName);

From the syntax above, we can notice the similarity between the addEventListener method.

Parameters

  • event − The type of event. For example, focus.

  • function − The function that executes when the event occurs.

Example

In this program, we have registered events in the head section. We have added both the event listener method and the event attach method. When a user clicks on the button, the button text is changed and displayed to the user.

<html> <head> <script type="text/javascript"> function onEventAttach (){ ataBtn.innerHTML = "Event Registered"; } function doAddEvent() { var ataBtn = document.getElementById ("ataBtn"); if (ataBtn.addEventListener) { ataBtn.addEventListener ("click", onEventAttach, false); } else { if (ataBtn.attachEvent) { ataBtn.attachEvent ('onclick', onEventAttach); } } } </script> </head> <body onload = "doAddEvent();" > <h2>Register events using the <i>attachEvent()</i> method</h2> <button id = "ataBtn" style = "background-color:#fbbbbf ">Click on this button</button> </body> </html>

In this tutorial, we have learned three ways to register JavaScript events.

The assignment method is very simple. But it allows adding only one handler per element. HTML attribute event registration is not a good method to use.

Adding an event listener is more convenient to use and allows for adding more than one event handler to one element. Only when we need to register events in IE8 or above versions can we go for the attachEvent method.


Advertisements