CPCODELAB
JavaScript

Events and Event Delegation

11 min read

Events

Events are signals fired by the browser when something happens — a click, keypress, form submission, scroll, etc. You attach event listeners to react to them.

javascript
const btn = document.querySelector("#btn");

function handleClick(event) {
  console.log("Clicked!", event.target);
  event.preventDefault();   // stop default action (e.g. form submit)
  event.stopPropagation();  // stop event bubbling up
}

btn.addEventListener("click", handleClick);

// Remove listener (must pass same function reference)
btn.removeEventListener("click", handleClick);

// Common events: click, dblclick, mouseenter, mouseleave,
// keydown, keyup, keypress, input, change, submit,
// focus, blur, scroll, resize, load, DOMContentLoaded

Event Bubbling and Capture

Events bubble up the DOM tree by default — a click on a <button> inside a <div> fires the click handler on both. The third argument to addEventListener (true) switches to capture phase (top-down).

Event Delegation

Instead of attaching listeners to each child element, attach one listener to a parent and use event.target to determine what was clicked. This is more efficient and works for dynamically added elements.

javascript
const list = document.querySelector("#item-list");

list.addEventListener("click", (e) => {
  // Only handle clicks on .delete-btn
  if (!e.target.matches(".delete-btn")) return;

  const li = e.target.closest("li");
  li?.remove();
});

// Works even for items added after page load!

Event delegation is the standard pattern in frameworks like React (which does it automatically under the hood). Getting comfortable with it makes reading framework source code much easier.

Ready to test yourself?
Practice JavaScript— quiz & coding exercises