Mitrovic Srdjan
Mitrovic Srdjan

Reputation: 149

Add/Remove classes using jQuery

I have few tabs defined and wrapper around a tag. They contain several elements like spans, img etc. My idea is to add class ACTIVE for clicked tab and remove it from previous tab so that only one is active at any point of time. The code I use is working

     <script>
     $(document).ready(function() {
         $(".tabs").click(function() {
            $(this).toggleClass("active");

         });
     });

But this is just part of solution. Its adding class to tab but it does not remove it from previous clicked tab. So if I have 3 tabs and click on each, all will be selected. Any easy fix for this?

Upvotes: 2

Views: 53

Answers (2)

Amit
Amit

Reputation: 15387

You can also try this

$(".tabs").on('click',function() {
   $(".tabs").removeClass("active");
   $(this).addClass("active");
});

About on: Attach an event handler function for one or more events to the selected elements.

Upvotes: 0

TysonWolker
TysonWolker

Reputation: 436

$(".tabs").click(function() {
     $(".tabs").removeClass("active");
     $(this).addClass("active");
});

Upvotes: 3

Related Questions