StopPropagation () "Prevents DOM Tree Bubbles": What does this mean?

I really don't understand what e.stopPropagation () does.

If I have a link using return false for the handler, I should get what I want (prevent the default behavior of the link, so it doesnโ€™t โ€œcallโ€ the following href location):

 <a id="myLink" href="http://www.google.com">Go to google</a>โ€‹ $('#myLink').click(function (e) { alert("No, you don't go to Google"); return false; });โ€‹ 

Adding e.stopPropagation() , what can I get? Can you give me a convincing example showing me what e.stopPropagation() can do?

+4
source share
4 answers

Easy, stopPropagation stops any events bubbling up to its container, container container, etc. etc.

Here is a live example: http://jsfiddle.net/5B7sw/

HTML:

 <div id="container"> <button id="propagate">Propagate</button> <button id="nopropagate">Do not Propagate</button> </div> 

and js:

 $('#container').click(function(){ console.log('container click') ; }); $('#propagate').click(function(){ console.log('propagateclick'); }); $('#nopropagate').click(function(e){ console.log('nopropagateclick'); e.stopPropagation(); }); 

Pressing the Distribution button (default behavior) will record the spread of the click and hold back to the console. Pressing a button that includes an e.stopPropagation() call will not print a โ€œclick click containerโ€ message because propagation to the container has been stopped.

+10
source

In your example, e.stopPropagation() will not do anything.

e.stopPropagation() can be used in the case of a nested element so that another element does not receive an event.

+1
source

This is not what you think.

stop propogation means that the same event will not propagate to its parent tag.

0
source

event.stopPropagation () will prevent bubbles from appearing through their ancestors. This means that any handlers attached to the ancestors using . Delegate () or . live () corresponding to this child will not fire. Here is a demonstration of this fact: http://jsfiddle.net/fSBGC/6/

0
source

All Articles