🌐 JavaScript DOM & Browser BOM
Estimated reading: 4 minutes 10 views

⚡ JavaScript – Events, addEventListener, Delegation & Custom Events: The Complete Guide


🧲 Introduction – Why JavaScript Events Matter

JavaScript events power every interaction on a website—whether it’s clicking a button, typing in a form, or hovering over a menu. Mastering event handling is essential to building dynamic, interactive applications.

By the end of this guide, you’ll understand:

  • ✅ What events are and how to listen for them
  • ✅ How addEventListener works
  • ✅ How to implement event delegation efficiently
  • ✅ How to create and dispatch custom events

🔔 1. What is an Event in JavaScript?

An event is a signal that something has happened in the browser—like a click, key press, mouse movement, form submit, etc.

✅ Example: Basic Click Event

document.querySelector("button").onclick = function () {
  alert("Button clicked!");
};

📘 This sets an inline event handler for a button click. However, this approach is less flexible than addEventListener.


🎧 2. Using addEventListener()

addEventListener() is the modern, preferred method for attaching events.

✅ Syntax:

element.addEventListener(event, handler, options);
ParameterDescription
eventEvent type like 'click', 'submit', 'keydown'
handlerCallback function to execute
options (optional)Object or boolean (e.g., { once: true })

✏️ Example: Click Event Listener

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

btn.addEventListener("click", () => {
  console.log("Clicked!");
});

✅ Flexible, allows multiple handlers on the same event.


💡 Advanced Example: Remove Event Listener

function greet() {
  console.log("Hello!");
  btn.removeEventListener("click", greet); // Removes itself
}

btn.addEventListener("click", greet);

✅ Ideal for one-time tasks or toggles.


🧪 3. Event Object & Properties

Every event triggers an event object, which contains useful info.

element.addEventListener("click", function (e) {
  console.log(e.target);  // Element that triggered the event
  console.log(e.type);    // Type of event, e.g., "click"
});

✅ Use event.preventDefault() to stop default browser actions, and event.stopPropagation() to prevent event bubbling.


🌿 4. Event Propagation: Bubbling vs Capturing

JavaScript events propagate in two phases:

PhaseDescription
CapturingFrom the outermost element down to the target
BubblingFrom the target element up to the root

By default, addEventListener() listens during bubbling.


🔁 Example: Bubbling

document.body.addEventListener("click", () => {
  console.log("Body clicked");
});

document.getElementById("inner").addEventListener("click", () => {
  console.log("Inner clicked");
});

✅ Clicking inner triggers both listeners due to bubbling.


🔗 5. Event Delegation – Efficient Event Handling

Instead of adding events to many child elements, add it to a common ancestor and use event.target.

✅ Use Case: Delegating to a <ul>

<ul id="list">
  <li>Item 1</li>
  <li>Item 2</li>
</ul>
document.getElementById("list").addEventListener("click", (e) => {
  if (e.target.tagName === "LI") {
    alert(`You clicked ${e.target.textContent}`);
  }
});

✅ Saves performance by using a single listener for dynamic elements too!


🎯 6. Creating Custom Events

You can define and dispatch your own events with CustomEvent.

✅ Example: Create & Dispatch Custom Event

const myEvent = new CustomEvent("launch", {
  detail: { mission: "Apollo 11" },
});

document.addEventListener("launch", (e) => {
  console.log("Mission:", e.detail.mission);
});

document.dispatchEvent(myEvent);

✅ Custom events can carry data (detail) and be used for decoupled communication between components.


📄 Event Listener Options

OptionDescription
onceRun the listener only once
captureListen during capturing phase
passiveTells browser not to block scroll behavior
element.addEventListener("touchstart", handler, { passive: true });

✅ Helps improve performance on scroll events.


💡 Best Practices

  • ✅ Use addEventListener() for clean, flexible code
  • ✅ Always remove listeners in long-lived apps to avoid memory leaks
  • ✅ Use delegation for large or dynamic DOM structures
  • ✅ Avoid inline handlers (onclick="...")—they’re harder to maintain
  • ✅ Always reference event.target for accuracy in delegation

📌 Summary

Let’s recap:

✅ JavaScript events power all browser interactivity
addEventListener() is the preferred modern approach
✅ Event delegation improves performance for dynamic UIs
✅ Custom events allow component-level communication
✅ Always clean up event listeners to avoid memory leaks


❓ FAQs

❓ What is the difference between onclick and addEventListener?

  • onclick can only assign one handler
  • addEventListener supports multiple handlers and extra options like once and capture

❓ How does event delegation improve performance?

It reduces the number of event listeners by leveraging event bubbling—ideal for dynamic lists or tables.

❓ How do I prevent the default action of an event?

Use event.preventDefault(), for example:

document.querySelector("form").addEventListener("submit", (e) => {
  e.preventDefault();
});

❓ What is event.target vs event.currentTarget?

  • event.target: The actual element that triggered the event
  • event.currentTarget: The element the listener is attached to

❓ When should I use Custom Events?

Use them to decouple components and trigger custom behaviors like “modal:open”, “user:login”, etc.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

JavaScript — Events / addEventListener / Delegation / Custom Events

Or Copy Link

CONTENTS
Scroll to Top