Event listeners are how JavaScript responds to things happening on the page — a click, a key press, a form submission, the page finishing loading. Without them, a web page could display information but could never react to anything the user does. addEventListener() is the standard, modern way to attach this kind of behavior to an element.

Basic Syntax

<!-- HTML -->
<button id="save-btn">Save</button>
const button = document.querySelector("#save-btn");

button.addEventListener("click", function () {
  console.log("Button was clicked!");
});

Output (printed to the console each time the button is clicked):

Button was clicked!

addEventListener() takes the event name as a string (no "on" prefix — just "click", not "onclick") and a function to run when that event fires. You can attach multiple listeners to the same element and event without one overwriting the other, which is a real advantage over the older element.onclick = ... style.

The Event Object

The listener function automatically receives an event object describing what happened — which element triggered it, which key was pressed, the mouse position, and more:

<input id="search" type="text" />
const input = document.querySelector("#search");

input.addEventListener("input", function (event) {
  console.log("Current value:", event.target.value);
});

event.target is especially useful — it always refers to the exact element the event happened on, which matters a lot once you start listening for clicks on a parent element that contains many children (see event bubbling for more on that).

Common Event Types

A few events cover the vast majority of real interactions: click (buttons, links), input (as the user types), submit (form submission), keydown/keyup (keyboard), mouseenter/mouseleave (hover), and DOMContentLoaded on document itself, which fires once the page's HTML has fully loaded — the standard place to put setup code that needs the DOM to already exist.

Removing a Listener

function handleClick() {
  console.log("Clicked once");
  button.removeEventListener("click", handleClick);
}

button.addEventListener("click", handleClick);

To remove a listener, you need a reference to the exact same function you passed in — which is why it's defined separately here rather than as an inline anonymous function. Passing a new anonymous function to removeEventListener will silently do nothing, since it's treated as a completely different function.