Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stopPropagation() "Prevents the event from bubbling up the DOM tree" : what does it means?

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

If I have a link using return false to the handler I should get what I want (prevent the default link behaviour, so it doesnt "call" the next 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 to me a solid example showing to me what e.stopPropagation() can do?

like image 282
markzzz Avatar asked Jun 08 '12 09:06

markzzz


People also ask

What does the event stopPropagation () method do?

stopPropagation() The stopPropagation() method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases.

Which method prevent the event from bubbling up the DOM tree?

stopPropagation()Returns: undefined. Description: Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

What is the use of stopPropagation method for stopping event bubbling )?

stopPropagation() method stops the bubbling of an event to parent elements, preventing any parent event handlers from being executed.

What does the stopPropagation () function in Javascript do *?

The stopPropagation() method prevents propagation of the same event from being called. Propagation means bubbling up to parent elements or capturing down to child elements.


2 Answers

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

Here's 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();
});

Clicking the button title "propagate" (default behaviour) will write "propagate click" and "containerclick" to the console. Clicking the button which includes a call to e.stopPropagation() will not print the "container click" message as propagation up to the container has been halted.

like image 142
Jamiec Avatar answered Nov 04 '22 00:11

Jamiec


In your example e.stopPropagation() would do nothing.

e.stopPropagation() may be used in case of nested element to prevent other element from receiving the event.

like image 27
strah Avatar answered Nov 04 '22 01:11

strah