Skip to content

Event Listeners

The addEventListener() method attaches an event handler to an element without overwriting existing event handlers.

Syntax

element.addEventListener(event, function, useCapture);

Example

document.getElementById("myBtn").addEventListener("click", function() {
  alert("Hello World!");
});

You can also refer to an external named function:

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

function myFunction() {
  alert ("Hello World!");
}

Removing Listeners

You can remove an event listener using removeEventListener(). Note that this only works if you used a named function.

element.removeEventListener("mousemove", myFunction);

Common Events

  • click: User clicks.
  • mouseover / mouseout: User hovers.
  • keydown / keyup: Keyboard interaction.
  • submit: Form submission.
  • DOMContentLoaded: The DOM structure is fully loaded.

Why use this?

Using addEventListener separates your JavaScript from your HTML (Separation of Concerns), making your code cleaner and easier to maintain than onclick="...".