I was looking at http://www.quirksmode.org/js/events_order.html and it is ambiguous in this part:
In the Microsoft model you must set the event’s
cancelBubble
property totrue
.window.event.cancelBubble = true
In the W3C model you must call the event’s
stopPropagation()
method.e.stopPropagation()
This stops all propagation of the event in the bubbling phase.
So my question is:
e.stopPropagation()
stop it, or does that only work for the bubble phase?The stopPropagation() method prevents propagation of the same event from being called. Propagation means bubbling up to parent elements or capturing down to child elements.
14, returning false from an event handler will no longer stop event propagation. Instead, e. stopPropagation() or e. preventDefault() should be triggered manually, as appropriate.
To stop the click event from propagating to the <div> element, you have to call the stopPropagation() method in the event handler of the button: btn. addEventListener('click', (e) => { e. stopPropagation(); alert('The button was clicked!
The standard DOM Events describes 3 phases of event propagation: Capturing phase – the event goes down to the element. Target phase – the event reached the target element. Bubbling phase – the event bubbles up from the element.
Short answer: The order is:
If you call e.stopPropagation()
in the capture phase (by setting the addEventListener()
's 3rd argument to true
), it stops at 1, so 2 & 3 cannot receive it.
If you call e.stopPropagation()
in the bubble phase (by setting the addEventListener()
's 3rd argument to false
or just not assign it), the 1 & 2 already complete, so it just prevents the event from bubbling up from the level where you call stopPropagation()
.
No, an event listener doesn't stop any events from propagating, unless you explicitly tell it to. The part you're referring to deals with the bubble phase specifically. IE's model doesn't support event capturing - full stop. the capture phase is what precedes the bubbling phase:
Top of the DOM --->event--->traverses--->to--->[target]+[event]-| (capture phase)
/\ \/
|------------------------to--------back up----------------- (bubble up)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With