fervor [>]CODING & CURIOSITY
FERVOR LEARNING SYSTEMTUTORIALS
← JavaScript

JavaScript / 2 MIN READ

addEventListener()

Respond to user interactions with event listeners

From the original Fervor library. Examples may use older package versions.

##JavaScript Event Handling with addEventListener()

Introduction

Welcome to the FrOnt3nd Tutorials! In this tutorial, we’ll dive into the addEventListener() method, a fundamental tool in JavaScript for registering event listeners on HTML elements. By using addEventListener(), you can respond to various events triggered by user interactions and take appropriate actions in your web applications.

Syntax

The addEventListener() method has the following syntax:

target.addEventListener(type, listener[, options]);

Event Types and Listeners

  • target: The HTML element to attach the event listener to.
  • type: A string representing the event type to listen for (e.g., “click”, “keydown”).
  • listener: The function to execute when the event is triggered.

Options Parameter

The options parameter is optional and provides additional configuration for the event listener. It’s an object that can include various properties.

Capturing or Bubbling

You can specify whether the event should be handled in the capturing phase or the bubbling phase of the event propagation. The default value is false, indicating the bubbling phase. If set to true, the event is handled during the capturing phase:

element.addEventListener('click', myFunction, { capture: true });

Once

You can indicate that the event listener should only be executed once and then removed:

element.addEventListener('click', myFunction, { once: true });

Passive

Specify that the event listener won’t call preventDefault(), which can enhance scrolling performance on touch devices:

element.addEventListener('touchstart', myFunction, { passive: true });

Signal

You can control the order of execution for event listeners. By default, listeners execute in the order they were added. With the signal option set to true, the listener executes before other listeners:

element.addEventListener('click', myFunction, { signal: true });

Examples

Suppose you have a button with the id “myButton” and you want to add a click event listener to it:

const button = document.getElementById('myButton');

button.addEventListener('click', () => {
    alert('Button clicked!');
});

Conclusion

The addEventListener() method is a powerful tool for handling user interactions in JavaScript. By understanding its syntax, event types, and options, you can create interactive and responsive web applications. Whether you’re listening for clicks, key presses, or other events, the addEventListener() method is a key feature of modern web development.

For more information, refer to the MDN documentation on addEventListener.


Keep your curiosity going.Explore more JavaScript →
287 TUTORIALS · 22 TOPICSREADY