jQuery event bubbling

testndtv picture testndtv · Aug 4, 2011 · Viewed 40.4k times · Source

I want to understand how exactly to interpret bubbling. Does it mean going up the HTML code hierarchy or something else?

Secondly, I was going through an example and I could not understand the last part where it says

The P-based click handler listens for the click event and then prevents it from being propagated (bubbling up)

What does this mean?

Answer

AlienWebguy picture AlienWebguy · Aug 4, 2011

The concept of "bubbling up" is like if you have a child element with a click event and you don't want it to trigger the click event of the parent. You could use event.stopPropagation().

event.stopPropagation() basically says only apply this click event to THIS CHILD NODE and don't tell the parent containers anything because I don't want them to react.

Event Capturing:

               | |
---------------| |-----------------
| element1     | |                |
|   -----------| |-----------     |
|   |element2  \ /          |     |
|   -------------------------     |
|        Event CAPTURING          |
-----------------------------------

Event Bubbling:

               / \
---------------| |-----------------
| element1     | |                |
|   -----------| |-----------     |
|   |element2  | |          |     |
|   -------------------------     |
|        Event BUBBLING           |
-----------------------------------

If you are using live() or delegate() you will need to return false;, though it may not work. Read the quote below.

Per jQuery docs:

Since the .live() method handles events once they have propagated to the top of the document, it is not possible to stop propagation of live events. Similarly, events handled by .delegate() will propagate to the elements to which they are delegated; event handlers bound on any elements below it in the DOM tree will already have been executed by the time the delegated event handler is called. These handlers, therefore, may prevent the delegated handler from triggering by calling event.stopPropagation() or returning false.

In the past it was a platform issue, Internet Explorer had a bubbling model, and Netscape was more about capturing (yet supported both).

The W3C model calls for you be able to choose which one you want.

I think bubbling is more popular because, as stated there are some platforms that only support bubbling...and it sort of makes sense as a "default" mode.

Which one you choose is largely a product of what you are doing and what makes sense to you.

More info http://www.quirksmode.org/js/events_order.html

Another great resource: http://fuelyourcoding.com/jquery-events-stop-misusing-return-false/