Use stopImmediatePropogation
to prevent invoking of other listeners for the same event
Thursday, October 29, 2020
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:
- What is the order in which two event listeners attached to the same event target are called?
- 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 stopImmediatePropogation()
method. I have used the stopPropogation()
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.
Instructions
Use the stopImmediatePropogation()
method on the Event
to prevent subsequent event listeners from being called for the event target as well as preventing the propagation of the event
Use the stopPropagation()
method on the Event
object to prevent the propagation of the event during the capture and bubble phases
For cancellation of subsequent (added after the current event listener) event listeners to the event target
Code Examples
use stopImmediatePropagation()
where necessary
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
});
avoid using stopPropagation()
if subsequent event listeners for the event target should not be called
const el = document.getElementById('btn');
el.addEventListener('click', event => {
console.log('first was called');
event.stopPropagation();
});
el.addEventListener('click', event => {
console.error('second was called'); // 🛑 second event listener is still invoked
});
Have a question or comment?