jQuery toggleClass Method – .toggleClass() Tutorial

jQuery toggleClass Method – .toggleClass() Tutorial

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.

Syntax of jQuery toggleClass Method

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)
There is also a very similar method in jQuery called the jQuery toggle method. Learn that method also.
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).
  • Index – Returns the index position of the element in the set. Index starts from 0.
  • currentclass – Returns current class/classes of the element.
switch Optional.
It is a boolean value. If ‘true’ then class can only be added. If ‘false’ then class can only be removed.

Toggle a Class using jQuery .toggleClass method

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")
I have used jQuery .toggleClass() method to create a beautiful jQuery Tabs feature in my website.

Using ‘Function’ to toggle a Class using jQuery .toggleClass method

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.

Using ‘Switch’ parameter of jQuery .toggleClass method

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:

DOWNLOAD

SHARE THIS ARTICLE

  • linkedin
  • reddit
yogihosting

ABOUT THE AUTHOR

I hope you enjoyed reading this tutorial. If it helped you then consider buying a cup of coffee for me. This will help me in writing more such good tutorials for the readers. Thank you. Buy Me A Coffee donate