Toggle class in jQuery switching rather than appending

I'm trying to add a class to an element on click called 'activetab'. How can I make it so if you click tab2, you add the class, but then if you click tab3 it takes it off tab 2 and onto tab 3 and so on. At the minute it just appends it.

$(".tab2").click(function () {
    $(".tab2").addClass("activetab");
});

$(".tab3").click(function () {
    $(".tab3").addClass("activetab");
});

$(".tab4").click(function () {
    $(".tab4").addClass("activetab");
});

Answers 1

  • You can use removeClass() to remove the class. Also, all the handler can be combined to make a single handler which will add the activetab class to the clicked tab and remove it from other tabs.

    // Bind click event on all the tabs
    $(".tab2, .tab3, .tab4").click(function () {
        // Remove class from other tab
        $(".activetab").removeClass('activetab');
    
        // Add class to the current clicked tab
        $(this).addClass("activetab");
    });
    

Related Articles