Practical bubble event?
With or without jQuery (bearing in mind that you can handle bubble events without using a library), there are a number of scenarios in which you want to structure your code to take advantage of the bubbles.
One example: suppose you have a page where elements are created dynamically, but you want to handle a click on these elements. You cannot bind an event handler directly to them before they exist, but to bind individual handlers to them when they are created is a bit of a pain. Instead, attach an event handler to the container object: click events will bubble from individual elements in the container, but you can still indicate which element was clicked - jQuery simplifies this if you use the appropriate .on()
or .delegate()
syntax (or even .live()
if you have a really old version of jQuery) because it sets this
to the element with a click.
<div id="someContainer"></div> $("#someContainer").on("click", ".dynamicElement", function() {
This suggests that when you click an element with the "dynamicElement" class, which is a child of the "someContainer", the div does something. It will work regardless of whether the "dynamicElement" element existed when the page was loaded, was later added in response to some other user actions or, possibly, loaded using Ajax.
source share