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
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
- Select the element you want to watch.
- Define a handler function that runs when the event fires.
- Register the listener with
element.addEventListener(type, handler). - The browser calls your handler every time the event occurs.
- Remove the listener with
removeEventListenerwhen no longer needed.
Related terms
Related Resources
Related Lessons
- DOM
Event listeners are the core of DOM scripting
Related Projects
- Random Quote Generator
Use event listeners to trigger quote generation
Learn the fundamentals
Deepen your understanding with structured lessons on this topic.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.