Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Trickle-down" custom JavaScript events

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.

like image 583
Rolf Avatar asked Sep 24 '14 00:09

Rolf


People also ask

What is the difference between event bubbling and event capture?

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.

What are Javascript custom events?

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.

What is the difference between event capturing and event bubbling in Javascript?

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.


1 Answers

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

like image 109
John Kurlak Avatar answered Oct 03 '22 17:10

John Kurlak