Lets say we have a HTML structure like this
<div id="container"> <div id="nested"> <span id="someElement"></span> </div> </div>
...and our goal is to have an event listener on the #container
only ! So, we bind a listener (jQuery code)
$("#container").on('click', function(event) { alert("container was clicked"); });
That works of course, but my problem with this approach is that, since events usually bubble up, that listener will also fire if we actually click on #nested
or #someElement
. My current solution to only handle the click when the #container
is clicked is to compare this
with event.target
$("#container").on('click', function(event) { if(this === event.target) { alert("container was clicked"); } });
My question: Is that considered "best practice" ? Is there a better way with jQuery to accomplish the same result "out of the box" ?
Example in action: http://jsfiddle.net/FKX7p/
Event bubbling is a type of event propagation where the event first triggers on the innermost target element, and then successively triggers on the ancestors (parents) of the target element in the same nesting hierarchy till it reaches the outermost DOM element or document object (Provided the handler is initialized).
A bubbling event goes from the target element straight up. Normally it goes upwards till <html> , and then to document object, and some events even reach window , calling all handlers on the path.
Event bubbling is a method of event propagation in the HTML DOM API when an event is in an element inside another element, and both elements have registered a handle to that event. It is a process that starts with the element that triggered the event and then bubbles up to the containing elements in the hierarchy.
An alternative way to prevent events from bubbling up is to use event.stopPropagation();
$("#container").on('click', function(event) { alert("container was clicked"); }) .children().on('click', function(event) { event.stopPropagation(); });
I think the advantage of using this approach is that if you want to attach another event to the nested div, you can just use
$("#nested").on('click', function(event) { event.stopPropagation(); // some action }); $("#container").on('click', function(event) { alert("container was clicked"); });
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