1
votes

How do I trigger click on a child element without letting the click event bubble upto the parent & thereby create a infinite trigger loop of click event.

For example I have like this:

<li>
   <a> ... </a>
</li>

I want to trigger a click event on a whenever li is clicked, but to prevent infinite trigger loop, I should avoid event propagation upto parent. How do I do that ?

5

5 Answers

0
votes

Something like this?

$('li').on('click','a', function(e) {
    e.stopPropagation();

    // your code here...
});
0
votes

By using .stopPropagation() on the anchor you can stop the bubbling. You should be able to use something like:

$('a').click(function (e) {
    e.stopPropagation();
    console.log('link');
});
$('li').click(function () {
    $('a').click();
});

jsFiddle example

0
votes

You do not state exactly the behavior you want from the click on the link, but if you simply want to stop the click being handled at all, use preventDefault() on the event argument of click:

$('li').on('click','a', function(e) {
    e.preventDefault();
});

If you just want to stop the parent seeing the event use stopPropagation() instead:

$('li').on('click','a', function(e) {
    e.stopPropagation();
});

The other option is return false, which does the same as both preventDefault() and stopPropagation()

$('li').on('click','a', function(e) {
    return false;
});
0
votes

use event.stopPropagation()() in the event callback.

$('selector').click(function(event){
  event.stopPropagation()();    
})
0
votes

Parse the tag name on the parent click handler. (You could also look at class name or ID, among other event filters.) If desirable child tag is detected, then stop the propagation and return true so that this event runs. If desirable child tag is not detected, then prevent default event and return false. Thus, clicking on LI will trigger the click on A without a runaway event loop, and clicking on A will proceed properly without a runaway event loop either. Note also that you can't just fire the .click() event on the tag. You need to send it deeper into the native DOM element, using [0].click(), as I have shown below.

$('LI').click(function(e){
  var sTag = e.target.tagName.toUpperCase();
  if (sTag == 'A') {
    console.log('DEBUG: A click');
    e.stopImmediatePropagation();
    return true;
  } else {
    console.log('DEBUG: ' + sTag + ' click');
    e.preventDefault();
    // the following won't work without the [0]
    $(this).find('A')[0].click();
    return false;
});