O'Reilly logo

jQuery and JavaScript Phrasebook by Brad Dayley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Toggling Classes

$("span").on("click", function(){    $(this).toggleClass("active"); });

You can toggle classes on and off using the .toggleClass(className [, switch) method. In addition to the className, you can specify true or false for the optional switch parameter, indicating to turn the class on or off.

For example, to turn the active class and the inactive class off for all <span> elements, the code would be as follows:

$("span").toggleClass("active", true); $("span").toggleClass("inactive", false);

The following code provides a good example of using jQuery to dynamically toggle a class on and off when a user clicks on a <span> element. The click handler in lines 9–11 uses ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required