JavaScript Tutorial

Events

Event bubbling, capturing, preventDefault, and custom events

What are JavaScript Events?

An event is a signal that something has happened within the browser — a user clicked a button, a page finished loading, or a form was submitted. JavaScript allows you to listen for these signals and respond with a function.
javascript
const button = document.querySelector("#my-button");

// The listener function receives an EVENT object!
button.addEventListener("click", (event) => {
  console.log(`Button clicked at: ${event.clientX}, ${event.clientY}`);
});

The Event Object (e)

When an event occurs, the browser creates an Event Object containing metadata about the action:
  • event.target: The actual element that triggered the event.
  • event.type: The type of event (e.g., "click", "keydown").
  • event.key: The specific key pressed (for keyboard events).
  • event.preventDefault(): Stopping the default browser behavior (like a link opening or a form submitting).
javascript
const form = document.querySelector("#my-form");

form.addEventListener("submit", (e) => {
  e.preventDefault(); // Stop page refresh!
  console.log("Form data saved!");
});

Propagation: Bubbling vs. Capturing

When an event happens on an element (like a button inside a div), how does it travel through the DOM?
  1. Capturing Phase: The event travels down from window to the target.
  2. Bubbling Phase (Default): The event bubbles up from the target to the window.
javascript
const div = document.querySelector("div");
const btn = document.querySelector("button");

// Event bubbling! Clicking button ALSO triggers the div's listener.
div.addEventListener("click", () => console.log("Div clicked!"));
btn.addEventListener("click", () => console.log("Button clicked!"));

// To stop the bubble!
btn.addEventListener("click", (e) => {
  e.stopPropagation(); // Only "Button clicked!" will show!
});

Most Common Event Types

CategoryEventsDescription
Mouseclick, dblclick, mouseenter, mouseleaveMouse actions
Keyboardkeydown, keyup, keypressKeyboard typing
Formsubmit, change, input, focus, blurUser input
Windowload, resize, scroll, unloadPage/Browser actions

Custom Events

You can even create and trigger your own events for complex application logic!
javascript
// Build a custom event!
const myEvent = new CustomEvent("userLogin", {
  detail: { username: "Alpha" }
});

// Dispatch it!
document.dispatchEvent(myEvent);

// Listen for it anywhere!
document.addEventListener("userLogin", (e) => {
  console.log(`User logged in: ${e.detail.username}`);
});

Summary

FeatureMethod / Syntax
Listenel.addEventListener(type, callback)
Stop Defaultevent.preventDefault()
Stop Bubbleevent.stopPropagation()
Targetevent.target (Real element)
BubblingEvent travels UP the tree (default)
CapturingEvent travels DOWN the tree
Best ForUser interactivity, form validation, page lifecycle
Remove Listenerel.removeEventListener(type, callback)
Once{ once: true } (Run only the first time!)
Passive{ passive: true } (Performance boost for scrolling!)
Custom Datadetail object inside CustomEvent
LifecycleUse DOMContentLoaded to run JS safely
Key Codesevent.key for modern; event.code for physical key
PointerUse pointerdown for both Mouse and Touch!
UI UpdatesEvents are the trigger for most UI changes
DebuggingmonitorEvents(el) in Chrome console!
CaptureUse the 3rd argument true in addEventListener
Current Targetevent.currentTarget (Element the listener is on!)