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 () {

$(".tab3").click(function () {

$(".tab4").click(function () {

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
        // Add class to the current clicked tab

Related Articles