Can someone provide practical, everyday examples of event bubbling and event capturing in jQuery/javascript? I see all kinds of examples demonstrating these concepts but they always seem like things you'd never actually need in a regular web app.
Both descriptions and code snippets would be greatly appreciated.
Practical event bubbling?
With or without jQuery (bearing in mind that you can handle bubbled events without using a library) there are a number of scenarios where you'd want to structure your code to take advantage of bubbling.
One example: let's say you have a page where elements are being created dynamically, but you want to process a click on those elements. You can't bind an event handler directly to them before they exist, but binding individual handlers to them when you create them is a bit of a pain. Instead, bind an event handler to a container object: click events will bubble up from the individual elements to the container but you can still tell which element was clicked - jQuery makes this easy if you are using the appropriate syntax of .on()
, or .delegate()
(or even .live()
if you have a really old version of jQuery) because it sets this
to the clicked element.
<div id="someContainer"></div>
$("#someContainer").on("click", ".dynamicElement", function() {
// this is the element, do something with it
});
This says that on click of an element with the class "dynamicElement" that is a child of the "someContainer" div do something. It will work regardless of whether the "dynamicElement" element existed at page load, was added later in response to some other user action, or perhaps loaded with Ajax.
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