SNos
SNos

Reputation: 3470

Add class only to clicked element and it's children

I am trying to add a class to a div when another one is clicked. Whit the code I have when I click on one div all of the get the class added.

FIDDLE

My jQuery is:

$(".front").click(function (event) {
    // remove classes from all
    $('.front .back').not($(this)).removeClass('back-Active');
    // add class to the one we clicked
    $('.front .back').addClass("back-Active");
    event.stopPropagation();
});

How could I solve this?

Upvotes: 0

Views: 2556

Answers (2)

gurvinder372
gurvinder372

Reputation: 68393

By using the this reference to current element

 $(".front").click(function (event) {
        // remove classes from all
        $('.front .back').removeClass('back-Active'); //line changed to remove back-Active from all
        // add class to the one we clicked
        $(this).find('.back').addClass("back-Active"); //this line changed to add back-Active to only current element
        event.stopPropagation();
    });

If you want to add the class to .front element also, then try

 $(".front").click(function (event) {
        $('.front, .front .back').removeClass('back-Active'); 
        $(this).addClass("back-Active"); 
        $(this).find('.back').addClass("back-Active"); 
        event.stopPropagation();
    });

Upvotes: 3

Tushar
Tushar

Reputation: 87203

Use $(this) in the event handler to refer to the element that is clicked.

$('.back', this)              // Select the element inside clicked element having `back` class
    .addBack(this)            // Add clicked element to the set
    .addClass("back-Active"); // Add class on the elements

Updated Fiddle

$(document).on('click', function() {
    $('.back').removeClass("back-Active");
});


$(".front").click(function(event) {
    // remove classes from all
    $('.back-Active').removeClass('back-Active');
    // add class to the one we clicked
    $('.back', this).addBack(this).addClass("back-Active");
    event.stopPropagation();
});
.back-Active {
    transform: scale(1.0) !important;
    opacity: 1 !important;
    transition: 400ms ease;
}

.front {
    background-color: red;
    width: 100px;
    height: 100px;
    margin: 20px;
}

.back {
    transform: scale(0.0);
    opacity: 0;
    background-color: green;
    width: 100px;
    height: 100px;
    margin-top: -18px;
    transition: 400ms ease;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="front">
    AAA
    <div class="back">AAA-BACK</div>
</div>

<div class="front">
    BBB
    <div class="back">BBB-BACK</div>
</div>

<div class="front">
    CCC
    <div class="back">CCC-BACK</div>
</div>

<div class="front">
    DDD
    <div class="back">DDD-BACK</div>
</div>

Upvotes: 1

Related Questions