Description
The .toggleClass() method toggles between adding and removing one or more classes for the selected elements.
This method checks each element for the specified classes. The classes are added if missing, and removed if already set - This creates a toggle effect.
However, by using the "switch" parameter, you can specify to only remove, or only add a class
v1.0
This method has the form:
.toggleClass(class)
Return Value
This form returns a jQuery object.
v1.3
This method has the alternate form:
.toggleClass(class,switch)
Parameter | Description |
---|---|
class | (required) Specifies one or more class names to add or remove. To specify several classes, separate the class names with a space. |
switch | (optional) A Boolean value specifying if the class should be added (true), or removed (false). |
Return Value
This form returns a jQuery object.
Toggle Classes Using a Function
Using a function to specify which classes should be toggled for the selected elements.
v1.4
This method has the alternate form:
.toggleClass(function(index,class),switch)
Parameter | Description |
---|---|
function(index, class) | Specifies a function that returns one or more class names to add/remove.
|
switch | (optional) A Boolean value specifying if the class should be added (true), or removed (false). |
Return Value
This form returns a jQuery object.
Examples
Toggle between adding and removing the "main" class for p elements:
$("button").click(function(){
$("p").toggleClass("main");
});