254

If I have class .A and class .B and want to switch in between on button click, what's a nice solution for that in jQuery? I still don't understand how toggleClass() works.

Is there an inline solution to put it in onclick="" event?

1
  • 5
    Inline JS (onclick="") is bad. why don't you use jQuery to register a proper event handler (or a delegate/live event if you have lots of elements with the same handler) Commented Aug 9, 2011 at 19:51

7 Answers 7

595

If your element exposes class A from the start, you can write:

$(element).toggleClass("A B");

This will remove class A and add class B. If you do that again, it will remove class B and reinstate class A.

If you want to match the elements that expose either class, you can use a multiple class selector and write:

$(".A, .B").toggleClass("A B");
8
  • 3
    what if instead of element I want to put class A or B depending on the state? Commented Aug 9, 2011 at 19:50
  • 1
    Be aware that you should cache the object you are trying to toggle rather than select the elements each time, the most common usage for toggling classes being in a click handler. var $trigger = $(".A"); $trigger.on("click", function() {$trigger.toggleClass("A B")});
    – mummybot
    Commented Mar 27, 2015 at 8:53
  • 1
    @mummybot - flagged as condescending. Frédéric - what if the element doesn't have any class "from the start"? that is an important state as well.
    – vsync
    Commented Sep 21, 2015 at 22:33
  • 4
    This does not work anymore. Now adds and removes both classes at the same time.
    – Fabián
    Commented May 3, 2018 at 1:35
  • 1
    @FrédéricHamidi I don't know what I did wrong but it wasn't working when I tried. Now it seems fine. In my case, it added and removed both classes at the same time but it seems working now. Probably I messed up something else and it affected this function. I deleted my comment. Sorry for the confusion.
    – BurakUeda
    Commented Dec 12, 2019 at 6:05
47

Here is a simplified version: (albeit not elegant, but easy-to-follow)

$("#yourButton").toggle(function() 
{
        $('#target').removeClass("a").addClass("b"); //Adds 'a', removes 'b'

}, function() {
        $('#target').removeClass("b").addClass("a"); //Adds 'b', removes 'a'

});

Alternatively, a similar solution:

$('#yourbutton').click(function()
{
     $('#target').toggleClass('a b'); //Adds 'a', removes 'b' and vice versa
});
2
  • 3
    I belive this way of using toggle is depricated in jquery 2.0
    – vittore
    Commented May 9, 2016 at 14:35
  • 3
    Thanks vittore. It's obviously an older answer from 2011. I've updated the syntax accordingly. Commented May 9, 2016 at 14:36
5

The easiest solution is to toggleClass() both classes individually.

Let's say you have an icon:

    <i id="target" class="fa fa-angle-down"></i>

To toggle between fa-angle-down and fa-angle-up do the following:

    $('.sometrigger').click(function(){
        $('#target').toggleClass('fa-angle-down');
        $('#target').toggleClass('fa-angle-up');
    });

Since we had fa-angle-down at the beginning without fa-angle-up each time you toggle both, one leaves for the other to appear.

5

I've made a jQuery plugin for working DRY:

$.fn.toggle2classes = function(class1, class2){
  if( !class1 || !class2 )
    return this;

  return this.each(function(){
    var $elm = $(this);

    if( $elm.hasClass(class1) || $elm.hasClass(class2) )
      $elm.toggleClass(class1 +' '+ class2);

    else
      $elm.addClass(class1);
  });
};

// usage example:
$(document.body).on('click', () => {
  $(document.body).toggle2classes('a', 'b')
})
body{ height: 100vh }
.a{ background: salmon }
.b{ background: lightgreen }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
Click anywhere

4

Your onClick request:

<span class="A" onclick="var state = this.className.indexOf('A') > -1; $(this).toggleClass('A', !state).toggleClass('B', state);">Click Me</span>

Try it: https://jsfiddle.net/v15q6b5y/


Just the JS à la jQuery:

$('.selector').toggleClass('A', !state).toggleClass('B', state);
2

Toggle between two classes 'A' and 'B' with Jquery.

$('#selecor_id').toggleClass("A B");

1

Here's another 'non-conventional' way.

  • It implies the use of underscore or lodash.
  • It assumes a context where you:
    • the element doesn't have an init class (that means you cannot do toggleClass('a b'))
    • you have to get the class dynamically from somewhere

An example of this scenario could be buttons that has the class to be switched on another element (say tabs in a container).

// 1: define the array of switching classes:
var types = ['web','email'];

// 2: get the active class:
var type = $(mybutton).prop('class');

// 3: switch the class with the other on (say..) the container. You can guess the other by using _.without() on the array:
$mycontainer.removeClass(_.without(types, type)[0]).addClass(type);

Not the answer you're looking for? Browse other questions tagged or ask your own question.