jQuery's toggleClass function

Posted in Javascript -

While looking up something else in the jQuery documentation just now I discovered a useful function "toggleClass" to toggle a CSS class on and off. This post doesn't really offer anything more than what is in the jQuery documentation (the toggleClass manual page is here) but simply serves to draw your attention to this very useful function; I wish I'd know about it several months ago. I really must read the docs more...

Example usage

To toggle a CSS class on and off when a list item is clicked in an unordered list with id "foo", do the following, where "bar" is the name of the CSS class:

$("#foo li").click(function() {
    $(this).toggleClass("bar");
});

If the <li> already had the "bar" class assigned to it, when it is clicked it will remove the class. If it did not have the "bar" class assigned then it will add the class when clicked.

Working example

The following is a working example of the above. The class that is toggled makes the text red and bold. Try clicking some of the elements below and then clicking them again to toggle between states.

  • apples
  • bananas
  • oranges
  • pears

If you are viewing this is a feed reader click through to view this page in a web browser otherwise the above example will not work for you.



Related posts:


Comments