Skip to content

Event Listener

In one line

An event listener is a function registered to run when a specific event occurs on a specific element.

In simple words

An event listener is how you tell JavaScript "when this event happens on this element, run this function." You register one with element.addEventListener(eventType, handler). The listener stays active until you remove it or the element is destroyed.

A single element can have many listeners for different events — one for click, another for mouseenter, and so on. You can also have multiple listeners for the same event; they all run in the order they were added.

When you no longer need a listener, remove it with removeEventListener using the same event type and function reference. This prevents memory leaks in long-running applications, especially single-page apps where elements come and go.

Example

javascript
const input = document.querySelector("input");

function onInput(event) {
  console.log("Typed:", event.target.value);
}

// Register the listener
input.addEventListener("input", onInput);

// Later, remove it
input.removeEventListener("input", onInput);

addEventListener registers a handler; removeEventListener removes it. You must pass the same function reference to remove it.

How it works

  1. Select the element you want to watch.
  2. Define a handler function that runs when the event fires.
  3. Register the listener with element.addEventListener(type, handler).
  4. The browser calls your handler every time the event occurs.
  5. Remove the listener with removeEventListener when no longer needed.

Related terms

Related Resources

Related Lessons

  • DOM

    Event listeners are the core of DOM scripting

Related Projects

Learn the fundamentals

Deepen your understanding with structured lessons on this topic.

View lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary