Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery click() on a nested div

The code can probably explain this better than I can:

<div class="wrapper">
    <div class="inner1"></div>
    <div class="inner2"></div>
</div>

<script>
$('div').click(function(){
    var class_name = $(this).attr('class');
    do_something(class_name);
});
</script>

When I click on the inner1 div, it runs the do_something() with both the inner1 div AND the wrapper.

With the site being built, nested divs are going to happen a lot. Is there a dynamic way to fix this issue and only run the top level div (in this case inner1)?

like image 588
adam Avatar asked Sep 06 '11 18:09

adam


2 Answers

Use stopPropagation:

$('div').click(function(e){
    e.stopPropagation();
    var class_name = $(this).attr('class');
    do_something(class_name);
});

On the other hand: are you sure this is what you're trying to do? You might want to modify your selector ($('div')) to only target the DIV's you want.

like image 73
Joseph Silber Avatar answered Sep 28 '22 02:09

Joseph Silber


You need to prevent the event bubbling. With jQuery, you would do this:

$('div').click(function(e)
{
    e.stopPropagation();

    // Other Stuff
});
like image 23
Tejs Avatar answered Sep 28 '22 02:09

Tejs