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 ...

Get jQuery and JavaScript Phrasebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.