Listening for Events
Objectives
By the end of this chapter, you should be able to:
- Attach behavior to an element with
.addEventListener() - Read useful information off the event object a listener receives
- Remove a listener with
.removeEventListener()
💡 Why this matters: Everything else in this module builds on one function. Once you can listen for an event, you can respond to anything a user does.
Attaching a Listener
.addEventListener(eventType, handler) runs handler every time eventType happens on that element.
Given this HTML:
<button id="btn">Click me</button>
const btn = document.getElementById("btn");
btn.addEventListener("click", () => {
console.log("Button was clicked");
});
Nothing happens when this code runs, it only sets up the listener. The message logs later, whenever a user actually clicks the button.
The Event Object
The handler function automatically receives an event object with details about what happened. Give it a parameter name to use it (event and e are both common).
btn.addEventListener("click", (event) => {
console.log(event.type);
// click
console.log(event.target);
// <button id="btn">Click me</button>
});
event.type is the name of the event that fired. event.target is the actual element the event happened on, useful when the same handler is attached to more than one element, or when you’re not sure which specific element triggered it.
Removing a Listener
.removeEventListener(eventType, handler) undoes an .addEventListener() call. It only works if you pass the exact same function reference used when adding it, an inline arrow function can’t be removed this way, since there’s no way to refer back to it.
function logClick() {
console.log("Clicked");
}
btn.addEventListener("click", logClick);
// ... later ...
btn.removeEventListener("click", logClick);
After removal, clicking the button no longer runs logClick. This matters for things like a temporary listener that should only fire once or twice, or cleaning up after a piece of the page is removed.
Try It
Starter HTML for all three exercises:
<button id="save">Save</button>
- Select
#saveand attach a click listener that logs"Saved". - Inside that same listener, also log
event.typeto confirm it reads"click". - Store the handler function in a variable, attach it to
#save, then remove it with.removeEventListener(). Confirm clicking afterward does nothing.
Recap
.addEventListener(eventType, handler)attaches behavior to an element without overwriting any other listener already on it.- The handler receives an event object.
event.typeis the event name,event.targetis the element it actually happened on. .removeEventListener()needs the same function reference used to add the listener, which is why inline arrow functions can’t be removed this way.
Next lesson: the specific mouse, keyboard, and form events you’ll use most.