How to Add and Remove Event Listeners in JavaScript

Browsing any website is an activity full of events. Users moving their mouse is an event and so is users clicking anywhere on the website. Similarly, users typing something or resizing the browser window is also an event.

Programmers are required to write code to respond to different user events. How are they supposed to do that? Do the constantly execute a piece of code that checks if the user is moving the mouse and act accordingly? No, that is not very efficient. Instead, the system or browser itself is supposed to send some sort of signal to let the programmer know that an event is happening or has taken place.

This is where event listeners come into play. Events will usually be attached to specific elements where they were triggered. We attach event listeners or event handlers to elements, to whose events we want to respond.

In this tutorial, you will learn the basics of adding and removing event listeners in JavaScript.

Adding an Event Listener

As I mentioned earlier, any event that occurs will usually be tied to a specific element, a group of elements, or the entire browser window. The event may or may not be the result of user interaction. For example, the DOMContentLoaded event that fires after the HTML document has been completely parsed with scripts loaded and executed is not directly result of user actions. It just happens when a specific set of webpage data has loaded.

Other events like a mouse click on a link or a button, or the pressing of keys on a keyboard are more immediate and a direct result of user action.

All the objects that can fire any events will have an addEventListener(type, callback, options) method. This method has two required and one optional parameter. The optional parameter can either be an object or a boolean value.

The first parameter is the type of event that you want to be notified about for the given element.

The second parameter is the callback function that you want to execute whenever the said event happens.

The third parameter is an options object which you can use to control the behavior of the event listener. You can specify the following options in it:

  1. capturetrue means that the event listeners attached to this element will be triggered in the capturing phase before reaching down to the target DOM element. The default value is false so the listeners fire during the bubbling phase.
  2. oncetrue means that the event listener will be executed at most once after it has been added. The listener is automatically removed once invoked. This value defaults to false.
  3. passivetrue means that the handler for the listener will never call the preventDefault() method. This option defaults to false except under certain situations.
  4. signal—useful for providing an AbortSignal. No AbortSignal is associated with the listener by default.

We will now use the knowledge we gained so far to create a random number generator that generates random numbers within specific range on button clicks.

Consider the following markup:

1
<section class="wrapper">
2
  <h1>00</h1>
3
  <button class="gen">Generate (10-50)</button>
4
  <button class="gen-high">Generate (50-100)</button>
5
  <p class="log"></p>
6
</section>

We will create three event listeners here. One for each of the two buttons and one for the wrapper section. A click on the first button should produce a random number between 10 and 50. Repeated clicks will result in new random numbers. A click on the second button should produce a random number between 50 and 100 but this will only work once. The section wrapper will only be capturing the clicks on the buttons.

Here is the JavaScript to accomplish all this:

1
const gen_btn = document.querySelector("button.gen");
2
const gen_high_btn = document.querySelector("button.gen-high");
3
const heading = document.querySelector("h1");
4
const log = document.querySelector("p.log");
5
const section = document.querySelector("section.wrapper");
6

7
gen_btn.addEventListener("click", function(event) {
8
  log.innerText += '|Clicked (Button 10-50)|';
9
  let r_num = Math.floor(Math.random()*40) + 10;
10
  heading.innerText = r_num;
11
});
12

13
gen_high_btn.addEventListener("click", function(event) {
14
  log.innerText += '|Clicked (Button 50-100)|';
15
  let r_num = Math.floor(Math.random()*50) + 50;
16
  heading.innerText = r_num;
17
}, {
18
  once: true
19
});
20

21
section.addEventListener("click", function(event) {
22
  log.innerText += '|Captured Click|';
23
}, {
24
  capture: true
25
});
26

27
section.addEventListener("click", function(event) {
28
  log.innerText += '|Bubbled Click|';
29
});

The high number generator button works only once because we have set the value of once to true inside our options object. The first event handler for the section triggers before the button click callback because its capture option has been set to true. The other one is triggered upon bubbling after button click handler.

This is evident from the log once you have clicked on the buttons in the demo below:

Removing an Event Listener

In the previous section, we created event listeners for multiple elements and we were able to use the once option to even make sure that a particular listener only works once. However, you can also remove an event listener manually whenever you want by simply calling the removeEventListener() method.

This method has two required and one optional parameter. The first parameter determines the type of listener and the second parameter is the name of the event listener function. The optional third parameter is an object or boolean value that determines if you want to remove a captured on uncaptured listener.

It is important to note that the options passed to addEventListener() allowed you control a variety of behavioral attributes like once, capture, and passive. The removeEventListener() method only takes capture into consideration.

We will have to make minor changes to our code here. For example, the event listener callback can no longer be an anonymous function because we will need a reference to it for the removeEventListener() method.

1
function updateNumber() {
2
  log.innerText += '|Clicked (Button 10-50)|';
3
  
4
  let r_num = Math.floor(Math.random()*40) + 10;
5
  heading.innerText = r_num;
6
  
7
  if(r_num == 25) {
8
    gen_btn.removeEventListener("click", updateNumber);
9
  }
10
}
11

12
gen_btn.addEventListener("click", updateNumber);

With the above code, each click on the button will generate a new random number as long as we haven’t generated 25. Once we generate 25, we will detach our event listener from the button. Any further clicks will not generate new random numbers.

Final Thoughts

This tutorial covered the basics of event listeners in JavaScript. You can attach multiple types of listeners to the same element. It is also possible to have multiple handlers for the same type of event listener. We did attach two different handlers to our wrapper section for the click event in this tutorial itself.

The use of options as the third parameter of addEventListener() allows us to control how the listeners will behave. Once we no longer need any listeners, we can remove them using the removeEventListener() method.


Source link