“Delegation” and “bubbling” are terms that gets thrown round a lot in JavaScript; but what exactly do these terms mean?
This is the first in a series of posts on bubbling, delegation and how to delegate events with jQuery; What does event bubbling mean, Event Delegation in JavaScript and Event Delegation with jQuery
Event Bubbling
In JavaScript, events bubble. This means that an event propagates through the ancestors of the element the event fired on. Lets show what this means using the HTML markup below;
<div>
<h1>
<a href="#">
<span>Hello</span>
</a>
</h1>
</div>
Lets assume we click the span
, which causes a click
event to be fired on the span
; nothing revolutionary so far. However, the event then propagates (or bubbles) to the parent of the span
(the <a>
), and a click
event is fired on that. This process repeats for the next parent (or ancestor) up to the document
element.
You can see this in action here. Click “Hello” and see the events as they get fired. The code used is shown below;
window.addEventListener("load", function () {
var els = document.querySelectorAll("*");
for (var i = 0; i < els.length; i++) {
els[i].addEventListener("click", function () {
alert('Click event fired on the ' + this.nodeName + ' element');
});
}
});
Note that I’m not interested in adding support to older versions of IE (<9). You’ll have to add the normal fallback to attachEvent
instead of addEventListener
if you want to support them, and find an alternative for querySelector
/ querySelectorAll
.
That’s all event bubbling is; an event fired on an element bubbles through its ancestor chain (i.e. the event is also fired on those elements). It’s important to note that this isn’t a jQuery feature, nor is it something that a developer must turn on; it’s a fundamental part of JavaScript that has always existed.
Ok, that’s a little bit of a lie… sort of.
By default, not all events bubble. For instance submit
does not normally bubble, nor does change
. However, jQuery masks this in the event handling code using all sorts of voodoo, so it will seem that they do bubble when using jQuery.
Now move onto the next article; Event Delegation in JavaScript
Pingback: What the F is a Event Bubble? | Web Developer Snippets
nice .. simple and easy language sir..
Thanks for this awesome explanation!!!! Would love to tweet this article out..was wondering if you would give your permission?
Hey Ingrid, sure… no problems! Glad the article helped :).