Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mastering event bubbling

Tags:

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/

like image 405
Andre Meinhold Avatar asked Sep 17 '12 12:09

Andre Meinhold


People also ask

What is meant by event bubbling?

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).

Do events bubble up or down?

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.

Why does event bubbling happen?

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.


1 Answers

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"); });​ 
like image 75
Mr. 14 Avatar answered Oct 02 '22 12:10

Mr. 14