Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore click event when clicked on children

Tags:

jquery

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

like image 782
Elie Avatar asked Oct 05 '10 13:10

Elie


People also ask

How do I prevent a parent's onclick event from firing when a child is clicked?

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.

How do I disable click event listener?

To disable clicks with JavaScript, we can write: const foo = document. querySelector('#foo') foo. addEventListener('click', (event) => { event.

How do I trigger a click event without clicking?

If you want native JS to trigger click event without clicking then use the element id and click() method of JavaScript.


2 Answers

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().

like image 170
Nick Craver Avatar answered Oct 02 '22 20:10

Nick Craver


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.

like image 28
Alin Purcaru Avatar answered Oct 02 '22 20:10

Alin Purcaru