So I have the following scenario:
<div id="block"> Sample text. <a href="#">Anchor link</a> </div> <script type="text/javascript"> $("#block").click(function() { alert('test'); }); </script>
When I click anywhere inside the div, I'm getting the 'test' alert. But, I want to prevent that from happening when I click on the "Anchor link". How can I implement that?
Thanks
Use stopPropagation method, see an example: As said by jQuery Docs: stopPropagation method prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
To disable clicks with JavaScript, we can write: const foo = document. querySelector('#foo') foo. addEventListener('click', (event) => { event.
If you want native JS to trigger click event without clicking then use the element id and click() method of JavaScript.
You can stop the clicks from bubbling up from links with an additional handler, like this:
$("#block a").click(function(e) { e.stopPropagation(); });
The the alternative we were discussing in comments:
$("#block").delegate('a', 'click', function(e){ e.stopImmediatePropagation(); }) .click(function() { alert('test'); });
This would prevent any child links from bubbling up (well, not really, but their handlers from executing), but not create a handler for each element, this is done via .stopImmediatePropagation()
.
This is what you need: http://api.jquery.com/event.target/ .
Just compare to check if the element was triggered by the element you want or one of its children.
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