DEV Community

Aman Kumar
Aman Kumar

Posted on

Handling Events and Event Propagation in JavaScript

🧪 Sample HTML Structure

Let’s start with a simple HTML page that includes a list of images:

<ul id="images">
  <li><img id="owl" src="owl.jpg" /></li>
  <li><a id="google" href="https://google.com">Google</a></li>
</ul>
Enter fullscreen mode Exit fullscreen mode

📌 3 Ways to Handle Click Events

1. Inline HTML (Not Recommended)

<img onclick="alert('Owl')" />
Enter fullscreen mode Exit fullscreen mode

❌ Not a clean or scalable approach.


2. Using onclick Property (Old Way)

document.getElementById('owl').onclick = function () {
    alert('Owl');
};
Enter fullscreen mode Exit fullscreen mode

Works, but limits flexibility (e.g., you can't attach multiple listeners).


3. ✅ Modern Way: addEventListener()

document.getElementById('owl').addEventListener('click', function () {
    alert('Owl');
});
Enter fullscreen mode Exit fullscreen mode

✔️ This is the preferred method. It allows multiple listeners, better control, and more modern event handling features.


🧱 The Event Object

document.getElementById('owl').addEventListener('click', function (e) {
    console.log(e);
});
Enter fullscreen mode Exit fullscreen mode

This logs the PointerEvent object, which gives you rich information like:

  • type – what kind of event occurred
  • target, srcElement, currentTarget
  • Mouse positions: clientX, clientY, screenX, screenY
  • Modifier keys: altKey, ctrlKey, shiftKey
  • timestamp, keyCode (for keyboard events)

🔁 Event Propagation

Bubbling (default):

Events bubble from the target element upward to its ancestors.

document.getElementById('images').addEventListener('click', function () {
    console.log('Clicked inside ul');
}, false);

document.getElementById('owl').addEventListener('click', function () {
    console.log('Clicked on owl');
}, false);
Enter fullscreen mode Exit fullscreen mode

Capturing:

Events flow top-down before reaching the target.

document.getElementById('images').addEventListener('click', function () {
    console.log('Captured on ul');
}, true);
Enter fullscreen mode Exit fullscreen mode

Stop Bubbling:

document.getElementById('owl').addEventListener('click', function (e) {
    e.stopPropagation();
    console.log('Clicked on owl');
});
Enter fullscreen mode Exit fullscreen mode

🔒 stopPropagation() prevents the event from reaching ancestor elements.


🚫 Preventing Default Behavior

Stop anchor tags from navigating:

document.getElementById('google').addEventListener('click', function (e) {
    e.preventDefault();
    console.log("Google link clicked, but not redirected.");
});
Enter fullscreen mode Exit fullscreen mode

🧼 Bonus: Remove Image on Click

Let’s say you want to remove an image when it's clicked. Here's how:

document.querySelector('#images').addEventListener('click', function (e) {
    if (e.target.tagName === 'IMG') {
        let removeIt = e.target.parentNode;
        removeIt.remove(); // Removes the <li> along with the image
    }
});
Enter fullscreen mode Exit fullscreen mode

🧹 This approach uses event delegation and works even if you add new images dynamically!


📘 Summary

Feature Description
addEventListener() Attach events cleanly
e.target Element that triggered the event
stopPropagation() Stops bubbling up the DOM
preventDefault() Cancels default browser behavior
Event Delegation Handle multiple similar events efficiently

Top comments (0)