jQuery's toggleClass function
Posted January 8th, 2010 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:
- jQuery: hide text when the page is loaded and show it later (Monday, June 21st 2010)
- Using ellipsis with HTML and CSS (Saturday, December 5th 2009)
- Minify Javascript and CSS with YUI Compressor (Friday, September 25th 2009)
- Force reload of updated CSS and Javascript files with unique filenames (Friday, March 20th 2009)
- Adding, removing and checking if an element has a CSS class with jQuery (Tuesday, December 16th 2008)
- Style an HTML form input with CSS and jQuery (Saturday, July 26th 2008)

Comments
blog comments powered by Disqus