cup_of cup_of - 3 months ago 10
CSS Question

Select single slider element through jQuery instead of all

I have a slider and each slide is a

<div>
. For each slide, I would like to toggle a class on it whenever it is clicked. But the problem is that when I click on a slide it is adding class on all slides instead of one that is clicked. How it can be fixed?

Below is my code:

HTML:

<div class="selling-box-slider">
<div class="selling-box-slide"></div>

<div class="selling-box-slide"></div>

<div class="selling-box-slide"></div>
</div>


CSS:

.selling-box-slide {
background-color: #000;
height: 403px;
}

.selling-box-clicked {
background-color: #fff !important;
}


jQuery:

jQuery(".selling-box-slide").click(function() {
jQuery('.selling-box-slide').toggleClass('selling-box-clicked');
});

Answer

Use this value inside click handler. this value inside an event handler refers to the target element which generated the event:

jQuery(".selling-box-slide").click(function() {
    jQuery(this).toggleClass('selling-box-clicked');
});