Question

I'm trying to fire a click event on the innermost element in the HTML tree, but since there is a click even tied to its parent container, both events are fired, which is not what I need. I have fixed this before with stopPropagation(), but I can't seem to get it to work today.

jQuery('#parent li').click(function() {
    jQuery(this).children('.contained').slideDown();
});
jQuery('.contained').click(function() {                 
    Query(this).slideUp();
});

and let's say here is our HTML:

<ul id="parent">
    <li>
        click to show more
        <p class="contained">click to hide</p>
    </li>
</ul>

I believe this won't validate since it has a p contained within an li, but let's ignore that momentarily for simplicity's sake. How can I have the inner element slideUp() without have the parent click even trigger it to slideDown() immediately after?

Was it helpful?

Solution

return false to stop the bubbling:

jQuery('.contained').click(function() {                 
    Query(this).slideUp();
    return false;
});

Note that returning false also prevent the default behavior of the event. Read more here.

Or use the event object's stopPropagation function:

jQuery('.contained').click(function(e) {                 
    Query(this).slideUp();
    e.stopPropagation();
});

OTHER TIPS

The answer is to stop the propagation of the event. You can use stopPropagation and its twin, stopImmediatePropagation to do this or you can both stop propagation and prevent the default action by returning false from the handler. The stopPropagation method will prevent event bubbling, that is, the propagation of the event up the DOM tree. The stopImmdiatePropagation will do that but also prevent other handlers at the same level from firing. Returning false is equivalent to using stopPropagation and preventDefault on the event.

Two ways to do it, stop the propagation or combine the two click handlers and adjust code according to event.target

Target method:

jQuery('#parent li').click(function(event) {
     var $tgt=jQuery(event.target)
    if (!$tgt.is('.contained') ){
         jQuery(this).children('.contained').slideDown();
    }else{
       $tgt.slideUp();
    }   
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top