Stfvns Stfvns - 2 months ago 63
CSS Question

Switch CSS class everytime user clicks - Jquery

I have 2 links with different CSS classes.
How can I switch between the two everytime a the user clicks?

<a class="class1" id="class1">Class1</a>
<a class="class2" id="class2">Class2</a>


It's just work one time, but when I click a second time, it doesn't work:

$("#class1").click(function(){
$("#class1").removeClass().addClass("class2");
$("#class2").removeClass().addClass("class1");
})

$("#class2").click(function(){
$("#class1").removeClass().addClass("class2");
$("#class2").removeClass().addClass("class1");
})


The CSS is to change the color

Answer

The methods are doing the same thing. You set the same class to each tag in both thats why it only works the first time. The second time it just resetting the current class. Shouldn't they be like this instead?

$("#class1").click(function(){
    $("#class1").removeClass().addClass("class2");
    $("#class2").removeClass().addClass("class1");
})

$("#class2").click(function(){
    $("#class1").removeClass().addClass("class1");
    $("#class2").removeClass().addClass("class2");
})