i have two links and want to toggle its class when click on any link.
my links are
<a id="single" class="btn" >
<a id="double" class="btn active">
so i want to change class from btn to btn active
i have this code
$(document).ready(function(){
$('a.btn').click(function(){
$(this).removeClass('focus active');
$(this).removeClass('active');
$(this).toggleClass("btn active");
});
});
I tried with this code because in some other javascript in my accpliceation is also adding these classes.
this work fine when its like bellow
<a id="single" class="btn" >
<a id="double" class="btn active">
but when my first button is active like bellow
<a id="single" class="btn active" >
<a id="double" class="btn">
this did't work but give classes as bellow when click on double
<a id="single" class="btn active" >
<a id="double" class="active">
this is strange cause its working when <a id="double"
is active but did't work when <a id="single"
is active.
all i want to do is when click on any link, 1. remove all classes from old link and give old link class "btn" 2. remove all classes from clicked link and give class "btn active"
how to fix this?
You just need to toggle class for the current clicked link, and before that, remove active and focus class for all links, like this:
$('a.btn').click(function(){
$("a.btn").removeClass("active focus");
$(this).toggleClass("active");
});
a.active {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="single" class="btn active">single</a>
<a id="double" class="btn">double</a>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With