Module 7: DOM and Browser APIs
Events, Event Listeners, and Delegation
Respond to user actions and manage events without unnecessary listeners.
Events let code react to actions such as clicks, form submission, keyboard input, and network completion. Register listeners with addEventListener rather than assigning multiple handlers to the same on... property.
const button = document.querySelector("#save-button");
button?.addEventListener("click", () => {
console.log("Save requested");
});
The event object contains information such as the event target and keyboard details. event.target is the originating element; event.currentTarget is the element whose listener is currently running.
Delegation#
Event delegation attaches one listener to a common ancestor and checks which descendant triggered the event. It works well for lists whose items are added dynamically.
const list = document.querySelector("#topics");
list?.addEventListener("click", (event) => {
if (!(event.target instanceof Element)) return;
const button = event.target.closest("button[data-topic]");
if (!button || !list.contains(button)) return;
console.log("Selected topic:", button.getAttribute("data-topic"));
});
Bubbling and default actions#
Many events bubble from the target toward ancestors. stopPropagation prevents further propagation; preventDefault prevents a browser's default action when that action is cancelable. Use these sparingly because they can interfere with expected browser behaviour.
Cleanup#
Long-lived components should remove listeners when they are no longer needed. You can pass an AbortSignal when registering listeners and abort the controller to remove a group of handlers.
Practice#
Make a list with several buttons and use one delegated click listener to identify which button was selected.