jQuery API

.toggleClass()

.toggleClass( className ) Returns: jQuery

Description: Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.

  • version added: 1.0.toggleClass( className )

    classNameOne or more class names (separated by spaces) to be toggled for each element in the matched set.

  • version added: 1.3.toggleClass( className, switch )

    classNameOne or more class names (separated by spaces) to be toggled for each element in the matched set.

    switchA Boolean (not just truthy/falsy) value to determine whether the class should be added or removed.

  • version added: 1.4.toggleClass( [switch] )

    switchA boolean value to determine whether the class should be added or removed.

  • version added: 1.4.toggleClass( function(index, class, switch) [, switch] )

    function(index, class, switch)A function that returns class names to be toggled in the class attribute of each element in the matched set. Receives the index position of the element in the set, the old class value, and the switch as arguments.

    switchA boolean value to determine whether the class should be added or removed.

This method takes one or more class names as its parameter. In the first version, if an element in the matched set of elements already has the class, then it is removed; if an element does not have the class, then it is added. For example, we can apply .toggleClass() to a simple <div>:

<div class="tumble">Some text.</div>
      

The first time we apply $('div.tumble').toggleClass('bounce'), we get the following:

<div class="tumble bounce">Some text.</div>
      

The second time we apply $('div.tumble').toggleClass('bounce'), the <div> class is returned to the single tumble value:

<div class="tumble">Some text.</div>

Applying .toggleClass('bounce spin') to the same <div> alternates between <div class="tumble bounce spin"> and <div class="tumble">.

The second version of .toggleClass() uses the second parameter for determining whether the class should be added or removed. If this parameter's value is true, then the class is added; if false, the class is removed. In essence, the statement:

$('#foo').toggleClass(className, addOrRemove);

is equivalent to:

if (addOrRemove) {
    $('#foo').addClass(className);
  }
  else {
    $('#foo').removeClass(className);
  }
  

As of jQuery 1.4, if no arguments are passed to .toggleClass(), all class names on the element the first time .toggleClass() is called will be toggled. Also as of jQuery 1.4, the class name to be toggled can be determined by passing in a function.

$('div.foo').toggleClass(function() {
  if ($(this).parent().is('.bar')) {
    return 'happy';
  } else {
    return 'sad';
  }
});

This example will toggle the happy class for <div class="foo"> elements if their parent element has a class of bar; otherwise, it will toggle the sad class.

Examples:

Example: Toggle the class 'highlight' when a paragraph is clicked.

<!DOCTYPE html>
<html>
<head>
  <style>

  p { margin: 4px; font-size:16px; font-weight:bolder;
      cursor:pointer; }
  .blue { color:blue; }
  .highlight { background:yellow; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <p class="blue">Click to toggle</p>
  <p class="blue highlight">highlight</p>
  <p class="blue">on these</p>
  <p class="blue">paragraphs</p>
<script>
    $("p").click(function () {
      $(this).toggleClass("highlight");
    });
</script>

</body>
</html>

Demo:

Example: Add the "highlight" class to the clicked paragraph on every third click of that paragraph, remove it every first and second click.

<!DOCTYPE html>
<html>
<head>
  <style>
  p { margin: 4px; font-size:16px; font-weight:bolder;
      cursor:pointer; }
  .blue { color:blue; }
  .highlight { background:red; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <p class="blue">Click to toggle (<span>clicks: 0</span>)</p>
  <p class="blue highlight">highlight (<span>clicks: 0</span>)</p>
  <p class="blue">on these (<span>clicks: 0</span>)</p>

  <p class="blue">paragraphs (<span>clicks: 0</span>)</p>
<script>
var count = 0;
$("p").each(function() {
  var $thisParagraph = $(this);
  var count = 0;
  $thisParagraph.click(function() {
    count++;
    $thisParagraph.find("span").text('clicks: ' + count);
    $thisParagraph.toggleClass("highlight", count % 3 == 0);
  });
});

</script>

</body>
</html>

Demo:

Example: Toggle the class name(s) indicated on the buttons for each div.

<!DOCTYPE html>
<html>
<head>
  <style>
.wrap > div { float: left; width: 100px; margin: 1em 1em 0 0;
              padding=left: 3px; border: 1px solid #abc; }
div.a { background-color: aqua; }
div.b { background-color: burlywood; }
div.c { background-color: cornsilk; }
</style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  
<div class="buttons">
  <button>toggle</button>
  <button class="a">toggle a</button>
  <button class="a b">toggle a b</button>
  <button class="a b c">toggle a b c</button>
  <a href="#">reset</a>
</div>
<div class="wrap">
  <div></div>
  <div class="b"></div>
  <div class="a b"></div>
  <div class="a c"></div>
</div>

<script>
var cls = ['', 'a', 'a b', 'a b c'];
var divs = $('div.wrap').children();
var appendClass = function() {
  divs.append(function() {
    return '<div>' + (this.className || 'none') + '</div>';
  });
};

appendClass();

$('button').bind('click', function() {
  var tc = this.className || undefined;
  divs.toggleClass(tc);
  appendClass();
});

$('a').bind('click', function(event) {
  event.preventDefault();
  divs.empty().each(function(i) {
    this.className = cls[i];
  });
  appendClass();
});
</script>

</body>
</html>

Demo:

Support and Contributions

Need help with .toggleClass() or have a question about it? Visit the jQuery Forum or the #jquery channel on irc.freenode.net.

Think you've discovered a jQuery bug related to .toggleClass()? Report it to the jQuery core team.

Found a problem with this documentation? Report it on the GitHub issue tracker

  • tmo

    You forgot to mention there is a duration parameter, too!

    • http://www.learningjquery.com/ Karl Swedberg

      There is no duration parameter for .toggleClass() in jQuery core. Maybe you’re thinking of jquery UI?

      • http://twitter.com/ScaredyCat Andy Powell

        Then the logic of getting to this page is wrong. I got here from:

        API Reference ->jQuery UI -> stable 1.8 -> effects -> Class transitions -> toggleClass

        I'd expect that still to be referring to jQuery UI not the core.

        • http://www.learningjquery.com/ Karl Swedberg

          Huh. I have no idea how you got here from there. There is no jQuery UI category in api.jquery.com, and following jqueryui.com to the toggleClass method brings me to http://jqueryui.com/docs/toggleClass/

          • http://twitter.com/ScaredyCat Andy Powell

            1.Go here: http://docs.jquery.com/

            2. Down the left, under API Reference, select JQuery UI

            3. On the right had side of the page that appears select Stable 1.8.

            4. Select the last entry, Effects, from the list of items under Stable 1.8

            5. Select Class transitions.

            6. See the title “UI/Effects/ClassTransitions”? – click toggleClass

            That entire path suggests it's part of UI not core.

          • http://www.learningjquery.com/ Karl Swedberg

            Thanks for that information. I can see how the UI documentation could appear misleading. It does say this: “The jQuery UI effects core extends the base class API to be able to animate between two different classes.” Nevertheless, it should be more explicit about what is jQuery UI and what is jQuery core, and it should be clear about where those links are pointing.

  • http://www.cnblogs.com/zhangziqiu ZQ

    in 1.4.1, the toggleClass() method allows us to set one or more class at one time:
    toggleClass(“foo bar”) or toggleClass(function(index,class){return “foo bar”}). Does the document need to update?

  • djati

    hello..
    at this Demo you mention..that only the selected

    that had clicked..which changed style..
    So, how i can toggle style of the other

    …i meant, for example, only one

    that should have the yellow color….or otherwise..

  • http://www.learningjquery.com/ Karl Swedberg

    Huh. I have no idea how you got here from there. There is no jQuery UI category in api.jquery.com, and following jqueryui.com to the toggleClass method brings me to http://jqueryui.com/docs/toggleClass/

  • http://www.learningjquery.com/ Karl Swedberg

    Huh. I have no idea how you got here from there. There is no jQuery UI category in api.jquery.com, and following jqueryui.com to the toggleClass method brings me to http://jqueryui.com/docs/toggleClass/

  • MetalPenguen

    This function can also be used to remove a class and add another one at the same command. e.g. for menus, you can switch the current menu item. At the following code, p1 would be ex-current item, while p2 is new-current item. Button clicks make p1 and p2 current (class red) in turn.

    jquery:
    $(“button”).click(function(){
    $(“#p1,#p2″).toggleClass(“red green”);
    });

    css:
    .red{color:red;font-weight:bold;}
    .green{color:green;}

    html:
    <p id=”p1″ class=”red”>rooster</p>
    <p id=”p2″ class=”green”>cat</p>
    <p id=”p3″ class=”green”>dog</p>
    <p id=”p4″ class=”green”>donkey</p>
    <button>Toggle classes for first two p elements</button>

  • Cloudream

    There is $.fn.toggleClass() without parameters, since 1.4 I think.

  • Cloudream

    There is $.fn.toggleClass() without parameters, since 1.4 I think.

  • Tcarnevale

    Is toggleClass(“classA classB”) supposed to toggle from original class to class A and then to ClassB?

    When I use
    $(“div.tumble”).click(function () {
    $(this).toggleClass(“bounce spin”);
    });

    I get div.spin on first click and div.tumble on second click, and so on, never obtaining div.bounce.

    Am I missing something?

    Thanks!

    Tom Carnevale

  • http://www.i4u2.biz I4u2

    thanks 4 share

  • Nate Kindrew

    The tricky part with what you're trying to do is that when you toggle the classes, if it wasn't there to begin with, it'll add the class. This means that you could potentially end up with both classes applied at the same time. My suggestion is to start with all of your links with the inactive_link class applied and then try the following for your onclick:

    $(“div#jur_menu > a”).click(function(){
    $(this).toggleClass(“active_link”).toggleClass(“inactive_link”);
    $(this).siblings(“.active_link”).toggleClass(“active_link”).toggleClass(“inactive_link”);
    });

    That should get rid of the existing class and replace it with whichever one wasn't applied already. Hope that helps.