Everything, Everywhere
Verified Specification | Standardized Formulas | Instant Precision
Secure & Private (Zero Data Retention) Free Access • No Sign-Up

Event Listeners

Events are signals that something happened in the browser, such as a button click or a key press.

Try It Yourself

      
📋 Copy JavaScript Event Delegation Pattern Snippet
// Event Delegation Pattern (Single Listener for Container)
const list = document.querySelector("#todo-list");

list.addEventListener("click", (event) => {
  const btn = event.target.closest(".btn-delete");
  if (!btn) return;
  const itemId = btn.dataset.id;
  deleteItem(itemId);
});

⚠️ 5 Fatal Traps & JavaScript Pitfalls

Trap #1: Attaching Individual Listeners to Hundreds of Elements
Attaching individual event listeners to every row in a table of 1,000 items creates 1,000 handler functions in memory. Use Event Delegation on the parent container.
Trap #2: Failing to Remove Event Listeners (Memory Leaks)
Passing an anonymous arrow function to addEventListener means you can never call removeEventListener because the function reference is lost.
Trap #3: Confusing event.target with event.currentTarget
event.target is the exact child element clicked. event.currentTarget is the parent element to which the event listener is currently attached.
Trap #4: Calling stopPropagation() Blindly
event.stopPropagation() breaks analytics tracking, modal backdrop dismissals, and parent delegators that rely on event bubbling up the DOM tree.
Trap #5: Janky Scrolling from Non-Passive Listeners
Touch and wheel listeners block browser compositor thread scrolling while waiting for JavaScript to complete. Always pass { passive: true } on scroll listeners.

💬 Frequently Asked Questions

What are the three phases of DOM event propagation?
1) Capturing phase (event travels down from window to target), 2) Target phase (event reaches target element), and 3) Bubbling phase (event bubbles back up the tree).
How does Event Delegation work and why is it important?
Event delegation binds a single listener to a parent container and inspects event.target using element.closest() to identify clicked children, saving memory and handling dynamically added elements automatically.
What does event.preventDefault() do?
It prevents the browser's default native action for the event (e.g. stopping form submission from reloading the page or link navigation).
How do you create and dispatch a custom event in JavaScript?
Create with const evt = new CustomEvent("userLogin", { detail: { userId: 42 }, bubbles: true }); and dispatch with element.dispatchEvent(evt);.
What is the once option in addEventListener?
Passing { once: true } automatically removes the event listener after it is invoked the first time, preventing duplicate executions.
Sponsored Utility
While You're Here
Sponsored Recommendations
Advertisement