DEV Community

Brian Love
Brian Love

Posted on • Originally published at lookout.dev

Use `stopImmediatePropogation` to prevent invoking of other listeners for the same event

I recently added an event listener to a DOM element. The element had another event listener for the same click event. Two questions came to my mind:

  1. What is the order in which two event listeners attached to the same event target are called?
  2. What if I want to prevent the second, or subsequent, event listener(s) from being called?

Let me share with you what I've learned.

First, I learned that, according to the DOM Level 3 specification, the order in which multiple event listeners attached to the same event target is determine by the order in which the event listeners were added. So, first-added-first-called if you will.

Second, I learned about the stopImmediatePropagation() method. I have used the stopPropagation() method in the past to prevent the propagation of the event during either the capture or bubble phases to the event target's ancestors. However, if the event target has multiple event listeners the stopPropagation() method will not prevent the other event listeners on the event target from being invoked.

This is where I learned that stopImmediatePropagation() method set's the stop immediate propagation flag, which instructs the JavaScript VM to no longer invoke event listeners on the event target as well as propagation of the event for the capture and bubble phases.

Let's look at an example of successfully using the stopImmediatePropagation() method:

const el = document.getElementById('btn');
el.addEventListener('click', event => {
  console.log('first was called');
  event.stopImmediatePropagation();
});
el.addEventListener('click', event => {
  console.error('second was called'); // 👍 second event listener is not invoked
});
Enter fullscreen mode Exit fullscreen mode

Check out more of my lookouts on lookout.dev where I learn in public.

I'm the Principal Architect at LoveLoveApp, an angular and react consulting company. If you need help with your Angular, React, or Node.js project, then hire the best for your project! Give us a shout and we'd love to learn about your project and how we can help.

Top comments (0)