jQuery - Add active class and remove active from other element on click
$(document).ready(function() {
$(".tab").click(function () {
if(!$(this).hasClass('active'))
{
$(".tab.active").removeClass("active");
$(this).addClass("active");
}
});
});
You can remove class active
from all .tab
and use $(this)
to target current clicked .tab
:
$(document).ready(function() {
$(".tab").click(function () {
$(".tab").removeClass("active");
$(this).addClass("active");
});
});
Your code won't work because after removing class active
from all .tab
, you also add class active
to all .tab
again. So you need to use $(this)
instead of $('.tab')
to add the class active
only to the clicked .tab
anchor
Updated Fiddle
Try this one:
$(document).ready(function() {
$(".tab").click(function () {
$("this").addClass("active").siblings().removeClass("active");
});
});
Try this
$(document).ready(function() {
$(".tab").click(function () {
$(".tab").removeClass("active");
// $(".tab").addClass("active"); // instead of this do the below
$(this).addClass("active");
});
});
when you are using $(".tab").addClass("active");
, it targets all the elements with class name .tab
. Instead when you use this
it looks for the element which has an event, in your case the element which is clicked.
Hope this helps you.