If you want to toggle between adding and removing classes from selected elements then use the jQuery toggleClass method.
Note that if an element does not have a particular class then this method will add that class to the element.
Else if the element already has that class then .toggleClass() will remove that class from the element.
It can have 3 types of syntaxes.
1. First Syntax
$(selector).toggleClass(classname)
2. Second Syntax
$(selector).toggleClass(classname, function(index,currentclass))
3. Third Syntax
$(selector).toggleClass(classname, function(index,currentclass),switch)
Parameter | Description |
---|---|
classname | Required. Specifies one or more class names to toggle. Separate multiple class names with a space. |
function(index,currentclass) | Optional. Function that returns one or more class names to add/remove (toggle).
|
switch | Optional. It is a boolean value. If ‘true’ then class can only be added. If ‘false’ then class can only be removed. |
Suppose you have a div and you want to toggle a class called redClass.
<div id="div1">Hello, How are you?</div>
The jQuery .toggleClass code would be:
$("#div1").toggleClass("redClass")
Now I will use the function parameter of jQuery toggleClass method.
Here I will toggle redClass of only even number of p elements.
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>
<p>Paragraph 4</p>
<p>Paragraph 5</p>
The jQuery Code for this will be:
$("p").toggleClass(function (index, currentclass) {
if (index % 2 == 0)
return "redClass";
});
The index % 2 == 0 condition checks for the even number of p element.
The switch parameter can take a Boolean value.
In the below code when passing true to the .toggleClass(), the redClass will only be applied but will not be removed.
<p>Paragraph 1</p>
$("p").toggleClass("redClass",true)
Similarly if I pass false then the redClass will only be removed and will not be added.
<p class="redClass">Paragraph 1</p>
$("p").toggleClass("redClass",false)
Visit the below links: