Plic Pl
Plic Pl

Reputation: 541

Same classes: Select child but not parent in Jquery

I have the following structure:

<div class="box blue">
    <div class="box red">

    </div>
    <div class="box green">

    </div>
</div>

Basically, there are boxes which can contain other boxes.

Now I want to archive, that if someone clicks on the parent box (blue) the background changes to white for example.

BUT, if someone clicks on the child box (red), the background of the childbox which was red should get white.

I have tried the following:

$('.box').click(function(){
    $(this).css({'background-color': '#fff'});
});

This doesnt work, because if I click on a child box for example, I trigger the click on the parent.

Does anyone know the solution?

Upvotes: 1

Views: 291

Answers (1)

Khamidulla
Khamidulla

Reputation: 2975

You should prevent event bubbling using

e.stopPropagation();

Fixed code as following:

$('.box').click(function(e){
    e.stopPropagation();
    $(this).css({'background-color': '#fff'});
});

Upvotes: 4

Related Questions