0

With the click of two buttons, I want to switch between two states, let's say state a and state b.

So I got two buttons:

<button id="btnA"> and <button id="btnB">

I also got some divs: bars, fx and table with some initial classes given. Let's say some classes are for state a and some for state b.

So when I click btnA I want the divs to get only the classes meant for state a and so when click btnB make the divs get only the classes meant for state b.

The problem here is that I really don't want switching or toggling, whatever similarities have.

I tried this:

$("#btnA").click(function() {

    $(this).removeClass("btn-default")
    $(this).addClass("btn-success")

    $("#btnB").removeClass("btn-success")
    $("#btnB").addClass("btn-default")

    $("#table").remove()
    $("#bars").switchClass("barsdiferencias barslagrange")
    $("#fx").switchClass("fxdiferencias fxlagrange")
})

$("#btnB").click(function() {

    $(this).removeClass("btn-default")
    $(this).addClass("btn-success")

    $("#btnA").removeClass("btn-success")
    $("#btnA").addClass("btn-default")  


    $("#graficos").append('<div id="table" class="table"></div>')
    $("#bars").switchClass("barslagrange barsdiferencias")
    $("#fx").switchClass("fxlagrange fxdiferencias")        

}) 

I have tried using switchClass and toggleClass but they don't do what I want. I know removing the unwanted classes and adding the proper ones at each function would make it. But, is there any fancier and shorter code solution?

3
  • I'm not sure I completely follow the question. Is it something like this: jsfiddle.net/X6sn3 Commented Mar 17, 2014 at 6:21
  • have you considered just putting one single "state" class on a containing element of all of those elements, and styling them based on that one class? Commented Mar 17, 2014 at 6:21
  • I'm new to CSS, can I define something like that for multiple DOM elements? Commented Mar 17, 2014 at 6:29

1 Answer 1

1

Try This

This just replaces the current class with the new one that you give in as parameter. The attr() method can be used to change any property of a tag.

    $(this).attr("class","btn-success")

    $("#btnA").attr("class","btn-default")  

To add more classes

    $(this).attr("class","classA classB")
Sign up to request clarification or add additional context in comments.

7 Comments

What when it comes to change between more than one?
you mean to add more classes?
Yes, exactly, for adding more than one class
to add more classes .attr("class","classA classB") .. have ediited my answer too
Yes it will just replace the class property
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.