My understanding of JS event propagation is that an event first "captures" down the DOM tree, then "bubbles" back up, triggering handlers along the way.
<html>
<body>
<div id="textbox">
nothing yet
</div>
</body>
<script>
// Gets incremented by "update" event
var val = 0;
// Event starts here
textbox = document.getElementById("textbox");
textbox.addEventListener("update", function(e) {
textbox.innerHTML = val;
}, false);
// Should bubble here
body = document.getElementsByTagName("body")[0];
body.addEventListener("update", function(e) {
val++;
}, false);
function update() {
var e = new Event("update");
textbox.dispatchEvent(e);
}
setInterval(update, 10);
</script>
</html>
In my code here there is a div "textbox" inside the body. I think the update event sent to the textbox should bubble up to the body, but it doesn't. The counter never updates.
If I set the UseCapture argument of the body's event listener to true, the counter updates.
Why does capturing work, but not bubbling?
If you use the old (unfortunately deprecated) way, it does bubble. See https://jsfiddle.net/py9vyr7h/1/
To get the effect you want (show nothing yet, then 0,1,2,...) you need to follow a couple of the previous answers, plus set capturing on the textbox. (otherwise you'll see show nothing yet, 1, 2,...). First you need to set bubbling to true on your event - like this:
Then you need to capture the event (set to true) - like this:
So everything looks like this:
You need to pass
{ bubbles: true }
as the second argument tonew Event( ... )
for the Event to bubble, as per the documentation on MDN, becausebubbles
defaults tofalse
.Updated jsfiddle example
dispatchEvent
dispatches your event. Summarizing, that meansTherefore, if the
bubbles
attribute is not true, the event won't bubble.You can set the
bubbles
attribute to true when you create the event withEvent
: