JQuery Add a class by click, but only allowed once.

Here is what I have so far: enter image description here

JavaScript:

$(document).ready(function() {
    $(".thumb_wrapper").click(function() {
        $(this).addClass("active");
    });
});

So this works, it adds a class, but I want only one element to be active at all times. Therefore, when I click on an element and becomes active, the next element that I click should be new active, and delete the class on the previous one.

It makes sense? How can I do something like this?

Thank!

+5
source share
5 answers

You need to remove the class activefrom your elements first thumb_wrapper. Try the following:

$(".thumb_wrapper").click(function() {
    $(".thumb_wrapper").removeClass("active");
    $(this).addClass("active");
});
+11
source

Download your shell and first call : removeClass()

var $wrapper = $(".thumb_wrapper");

$wrapper.click(function() {
    $wrapper.removeClass("active");
    $(this).addClass("active");
});
+3
source
$(".thumb_wrapper").on('click', function() {
    $(".thumb_wrapper").removeClass('active').find(this).addClass("active");
});
+1

.

$(document).ready(function() {
    $(".thumb_wrapper").click(function() {
        $(this).parent().children().each(function() { 
             $(this).removeClass("active");
         });
         $(this).addClass("active");
     });
});
0
$(document).ready(function(){
    $('.what').click(function(){
        $('.what').removeClass('active');
        $(this).addClass('active');       
   });       
});

- ?

0