HTML - addEventListener()

The addEventListener() method in JavaScript is used to attach an event handler to an HTML element. It listens for specific events (like clicks, keypresses, mouseovers, etc.) and runs a function when that event occurs.

 Syntax:

element.addEventListener(event, function, useCapture);

Parameters:

Parameter Description
event The name of the event to listen for (e.g., "click", "mouseover", "keydown").
function The function to run when the event occurs (called the callback).
useCapture (optional) A Boolean (true or false) that indicates whether the event should be captured in the capturing or bubbling phase. Default is false.

Basic Example:

HTML:

<button id="myBtn">Click Me</button>

JavaScript:

document.getElementById("myBtn").addEventListener("click", function() {
  alert("Button was clicked!");
});
  • This attaches a "click" event listener to the button with the ID myBtn.

  • When the button is clicked, it triggers an alert.

 Example with Named Function:

function sayHello() {
  console.log("Hello!");
}

document.getElementById("myBtn").addEventListener("click", sayHello);

 Example with Multiple Listeners:

You can attach multiple event listeners to the same element and event:

let btn = document.getElementById("myBtn");

btn.addEventListener("click", () => {
  console.log("First listener");
});

btn.addEventListener("click", () => {
  console.log("Second listener");
});

Example: Listening to Keyboard Events

document.addEventListener("keydown", function(event) {
  console.log("You pressed: " + event.key);
});

useCapture Example (Advanced):

parentElement.addEventListener("click", callback, true);  // Capturing phase
  • Use this only when you need fine control over event propagation.

 

  • addEventListener() is more flexible than HTML onClick attributes or old element.onclick properties.

  • It supports multiple handlers for the same event.

  • You can remove the listener with removeEventListener() if needed.