By the end of this lesson, you will be able to attach JavaScript behavior to browser events using addEventListener, read the event object, and prevent default browser actions safely.
What it is
An event listener is a function that waits for a specific event on a target element, document, or window. Events are signals: click, keydown, submit, load, and change. The addEventListener method registers a listener without replacing existing handlers. The browser calls your function when the event occurs and passes an Event object, often named e or event, containing details such as e.target, e.type, and methods like e.preventDefault() and e.stopPropagation().
Related terms: event target, event phase, handler, and event delegation.
Why it matters
- Separates behavior from markup, unlike inline
onclickattributes. - Allows multiple listeners for the same event on the same element.
- Gives access to the event object for keyboard keys, mouse coordinates, form data, and default action control.
- Supports cleanup with
removeEventListener, which is important in single-page applications. - Enables event delegation by listening on a stable ancestor element.
Syntax or steps
The smallest useful pattern is:
target.addEventListener("eventName", handler);
- Select the element or object that receives the event.
- Call
addEventListenerwith the event name as a string, without theonprefix. - Pass a function that accepts the event object.
- Inside the handler, use the event object to inspect or control the event.
Example
const form = document.querySelector("#signup");
form.addEventListener("submit", (e) => {
e.preventDefault();
const email = form.elements.email.value.trim();
if (!email.includes("@")) {
console.log("Please enter a valid email.");
return;
}
console.log("Submitting:", email);
});
Part by part:
document.querySelector("#signup")finds the form element.form.addEventListener("submit", ...)waits for the form submission event.e.preventDefault()stops the browser from reloading or navigating away.form.elements.email.valuereads the input namedemail.- The handler validates the value and logs a result instead of submitting normally.
Common mistakes
- Using
"onclick"instead of"click". Fix: event names do not includeon. - Calling the handler immediately:
form.addEventListener("submit", handleSubmit()). Fix: pass the function itself, not its result. - Forgetting
e.preventDefault()on form submit or link click. Fix: call it when JavaScript should handle the action. - Trying to remove an anonymous listener. Fix: store the function in a variable so
removeEventListenercan reference the same function.
When to use it
Compare addEventListener with the older on* property or inline HTML attributes.
| Approach | Best for | Limitation |
|---|---|---|
addEventListener |
Most JavaScript code, multiple handlers, cleanup, and options like capture | Slightly more verbose |
element.onclick = handler |
Quick one-off handlers | Replaces the previous handler |
Inline onclick="..." |
Rare demos | Hard to maintain and mixes markup with behavior |
Use addEventListener when you need predictable, composable behavior. Use on* only when a single handler is enough and you do not need options or removal.
Practice
Guided exercise: Add a listener to an input that logs the search text when the user presses Enter.
const input = document.querySelector("#search");
input.addEventListener("keydown", (e) => {
if (e.key === "Enter") {
console.log("Search for:", e.target.value);
}
});
Challenge: Prevent a link from navigating and log its href instead.
Solution hint: listen for "click", call e.preventDefault(), then read e.target.href.
Quick check
Question: What does e.preventDefault() do?
Answer: It cancels the browser's default action for that event, such as submitting a form or following a link, while still allowing your JavaScript code to run.
Summary
Event listeners connect user actions to JavaScript behavior. addEventListener is the standard way to attach handlers, and the event object gives you both information about the event and control over its default behavior.