Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Add Class on 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 is working, it is adding the class but I want only one item to be active at all times. So when I click on an item, and it turns active, the next item I click on should be the new active one, and remove the class on the previous one.

Does that make sense? How can I do something like this?

Thanks!

like image 846
Drew Avatar asked Apr 09 '12 15:04

Drew


3 Answers

You need to first remove the active class from your thumb_wrapper elements. Try this:

$(".thumb_wrapper").click(function() {
    $(".thumb_wrapper").removeClass("active");
    $(this).addClass("active");
});
like image 166
Rory McCrossan Avatar answered Nov 17 '22 20:11

Rory McCrossan


Cache your wrapper and call a removeClass() on it first:

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

$wrapper.click(function() {
    $wrapper.removeClass("active");
    $(this).addClass("active");
});
like image 3
Code Maverick Avatar answered Nov 17 '22 18:11

Code Maverick


$(".thumb_wrapper").on('click', function() {
    $(".thumb_wrapper").removeClass('active').find(this).addClass("active");
});
like image 1
adeneo Avatar answered Nov 17 '22 20:11

adeneo