JAVASCRIPT Tutorial

Multiple Event Listeners

Multiple event listeners allow an element to respond to multiple events or multiple functions for the same event.

Steps to add multiple event listeners:

  1. Identify the element: Determine which element you want to add event listeners to.
  2. Select events: Choose the events you want the element to listen for (e.g., "click," "hover").
  3. Create event listener functions: Write the functions that will be executed when the events occur.
  4. Add event listeners: Use the addEventListener() method to attach the event listeners to the element.

Order of Execution:

Event listeners execute in the order they are added. If multiple event listeners are attached to the same element for the same event, they will execute in that order.

Example:

const button = document.getElementById("my-button");

// Add event listener for click event
button.addEventListener("click", () => {
  console.log("Clicked");
});

// Add event listener for hover event
button.addEventListener("hover", () => {
  console.log("Hovered");
});

In this example:

  • The button element has two event listeners attached: one for the "click" event and one for the "hover" event.
  • When the button is clicked, both the "Clicked" and "Hovered" messages will be logged to the console in that order, as the "hover" event listener was added second.