Learning jQuery: toggleClass( )

I’m still a novice at jQuery, and recently had a chance to learn a little bit more, for a project I’m working on.

I’m still a novice at jQuery, and recently had a chance to learn a little bit more, for a project I’m working on.

Here’s the HTML (classes and ids simplified a bit):


And here’s the desired behavior: when the link is clicked, the parent div (ie: #base) should switch its class between “black” and “white”. What actually happens to the styles, we won’t get into here. My first attempt went like this:

$(document).ready(function(){
    $(".black a#toggle").click(function() {
      $("#base").removeClass("black");
      $("#base").addClass("white");
    });
    $(".white a#toggle").click(function() {
      $("div#base").removeClass("white");
      $("div#base").addClass("black");
    });
  });

But that wasn’t working. One click did toggle #base from “black” to white”, but a second click wouldn’t toggle it back to “black”. It looked like since the page was loaded with “black” as the div’s actual class, the click function was only bound to “.black a#toggle”. After a bit of experimentation and research, I found the answer: toggleClass(). So my code read like this:

$(document).ready(function(){
  $("a#toggle").click(function() {
     $("div#base").toggleClass("black");
     $("div#base").toggleClass("white");
  });
});

And that worked. Ah, but there’s a better way! toggleClass() (just like addClass() and removeClass(), as it turns out) can take a space-separated list of classes as its argument; each one of these classes will be toggled in the selected element(s). So, to switch between “light” and “dark” I just need a single line:

$(document).ready(function(){
  $("a#toggle").click(function() {
     $("div#base").toggleClass("black white");
  });
});

Easy-peasy! toggleClass() can do more than what I’ve show here, though! Read the official documentation for the full story.