Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery toggleClass not working

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?

like image 538
user3412718 Avatar asked Nov 30 '22 23:11

user3412718


1 Answers

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>
like image 114
xxxmatko Avatar answered Dec 04 '22 09:12

xxxmatko