Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why firing a defined event with dispatchEvent doesn't obey the bubbling behavior of events?

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 ?

like image 660
Shnd Avatar asked Apr 13 '14 20:04

Shnd


People also ask

Why is event bubbling important?

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).

How do you handle event bubbling?

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.

What is the difference between event bubbling and event capturing?

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.

Which of the following options would prevent an event from bubbling up in the DOM in a jquery event handler where event receives the event object?

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.


1 Answers

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

like image 110
Patrick Evans Avatar answered Oct 13 '22 01:10

Patrick Evans