I'm confused with the script below:
var event = new Event('shazam');
document.body.addEventListener('shazam',function(){
alert('body');
});
document.addEventListener('shazam',function(){
alert('document');
});
window.addEventListener('shazam',function(){
alert('window');
});
document.body.dispatchEvent(event);
When I run this script on my browser, I just get the alert('body'); event. but if i set the capturing parameter of addEventListener (the third optional parameter) to true, all the alerts captured in order they should.
Why the shazam event doesn't bubble up ?
Event bubbling is a type of event propagation where the event first triggers on the innermost target element, and then successively triggers on the ancestors (parents) of the target element in the same nesting hierarchy till it reaches the outermost DOM element or document object (Provided the handler is initialized).
Note: The event. stopPropagation () method stops the move upwards bubbling (on one event only), but all the other handlers still run on the current element. In order to stop the bubbling and also prevent the handlers from running on the current element, we can use event. stopImmediatePropagation () method.
Event Bubbling − Whenever an event happens on an element, the event handlers will first run on it and then on its parent and finally all the way up to its other ancestors. Event Capturing − It is the reverse of the event bubbling and here the event starts from the parent element and then to its child element.
To stop the bubbling and prevent handlers on the current element from running, there's a method event. stopImmediatePropagation() . After it no other handlers execute.
You need to set the bubbles
property to true, and you have to do this during the construction:
var event = new Event('shazam', { bubbles: true });
or the old way with initEvent
, passing true as the second argument to allow bubble:
event.initEvent('shazam', true);
MDN Doc
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