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?).
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.
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()Returns: undefined. Description: Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
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 } } );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With