Search code examples
javascriptjqueryeventsclickpropagation

Fire click event for only innermost element in jQuery


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?


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();
    });