Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery stopPropagation bubble down

I have a div with a link inside of it:

<div id="myDiv">     <a href="http://www.lol.com">Lol</a> </div> 

Clicking the <div /> should go somewhere, but clicking the child <a /> should go to www.lol.com. I've seen from previous questions and the jQuery website that .stopPropagation prevents bubbling upwards, but how do I prevent a bubble downwards (isn't that what's necessary here?).

like image 500
atp Avatar asked Apr 28 '10 09:04

atp


People also ask

What does event stopPropagation () do?

The event. stopPropagation() method stops the bubbling of an event to parent elements, preventing any parent event handlers from being executed. Tip: Use the event. isPropagationStopped() method to check whether this method was called for the event.

How does jquery handle event bubbling?

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.

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.


1 Answers

Events only bubble up. So the click event handler for the a element is fired before the click event handler for the div. If you want the behaviour you describe, the you need to add a click event handler to the a element which stops propagation to the div.

$("#myDiv a").click( function(event) {     event.stopPropagation(); } ); 

and keep whatever event handler you have on the div. This should allow the event to perform it's default action, and prevent the handler on the div being fired.

If you only want to prevent clicks on links then you can change your event handler for the div element

$("#myDiv").click( function( event ) {     if( !$( event.target ).is( "a" ) )     {         // existing event handler     } } ); 
like image 61
Geoff Avatar answered Oct 05 '22 00:10

Geoff