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

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

<div id="div1">Hello, How are you?</div>

The jQuery .toggleClass code would be:

$("#div1").toggleClass("redClass")

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)

DEMO DOWNLOAD

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on "WordPress, SEO, jQuery, HTML" and more.