JavaScript event listeners: handling user interaction
addEventListener, removeEventListener, event object, event.target vs event.currentTarget, event propagation, bubbling, capturing, stopPropagation, preventDefault, event delegation
Events Drive the Browser
Every user interaction — click, keypress, input, scroll — fires an event. addEventListener registers a function to run when a specific event occurs on a specific element. Understanding bubbling and delegation is essential for writing scalable event handling.
Adding and Removing Listeners
const btn = document.querySelector("#submit");
function handleClick(event) {
console.log("Clicked:", event.target);
}
btn.addEventListener("click", handleClick);
// Must pass the same function reference to remove
btn.removeEventListener("click", handleClick);
Event Bubbling and Propagation
document.querySelector(".modal").addEventListener("click", (e) => {
e.stopPropagation(); // stops click reaching document
});
document.querySelector("a.internal").addEventListener("click", (e) => {
e.preventDefault(); // stops default browser navigation
handleSPARoute(e.target.href);
});
Event Delegation
Instead of adding listeners to every list item, add one listener to the parent. When any child is clicked, the event bubbles up. Check event.target to identify which child was clicked. This is essential for dynamic lists where items are added and removed.
document.querySelector("#list").addEventListener("click", (e) => {
if (e.target.matches("li.item")) {
handleItemClick(e.target.dataset.id);
}
});
event.target vs event.currentTarget
event.target is the element that originally triggered the event. event.currentTarget is the element the listener is attached to. They differ when events bubble through a hierarchy.
