I'm looking into custom events in JavaScript.
According to MDN, using the CustomEvent constructor, there is an option to make the event "bubble up" (false by default):
https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent#CustomEventInit
Example:
// add an appropriate event listener
obj.addEventListener("cat", function(e) { process(e.detail) });
// create and dispatch the event
var event = new CustomEvent("cat", {"detail":{"hazcheeseburger":true}});
obj.dispatchEvent(event);
I tested it on jsfiddle:
http://jsfiddle.net/ppx4gcxe/
And the bubble up functionality seems to work. But I'd like my custom event to "trickle down", that is to trigger even listeners on child elements; the opposite of bubbling up.
I vaguely remember some default browser events "trickling down". This was supposedly one of these points of contention in the early browser days.
Anyway, is there any way to get this functionality on my custom events? Any relatively easy and straightforward way, of course. I don't really want to write a function to traverse all child elements and manually trigger any listeners on them. I hope there's another way.
With bubbling, the event is first captured and handled by the innermost element and then propagated to outer elements. With capturing, the event is first captured by the outermost element and propagated to the inner elements.
Custom events can be used to create “graphical components”. For instance, a root element of our own JS-based menu may trigger events telling what happens with the menu: open (menu open), select (an item is selected) and so on. Another code may listen for the events and observe what's happening with the menu.
Event Capturing is opposite to event bubbling, where in event capturing, an event moves from the outermost element to the target. Otherwise, in case of event bubbling, the event movement begins from the target to the outermost element in the file.
The behavior you're looking for is called event capturing
(the opposite of event bubbling
). You can enable event capturing
by passing in true
as the third argument to addEventListener
.
See: http://jsfiddle.net/zs1a6ywo/
NOTE: event capturing
is not supported in IE 8 or below.
For more information, see: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener
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