jQuery toggleClass()

The jQuery toggleCLass() method is used to add or remove one or more classes from the selected elements. This method toggles between adding and removing one or more class name. It checks each element for the specified class names. If the class name is already set, it removes and if the class name is missing, it adds.

In this way, it creates the toggle effect. It also facilitates you to specify to only add or only remove by the use of switch parameter.

Syntax:

Parameters of jQuery toggleClass() method

ParameterDescription
classnameIt is a mandatory parameter. It specifies one or more class name to add or remove. If you use several classes then separate them by space.
function (index, currentclass)It is an optional parameter. It specifies one or more class names that you want to add or remove.
  • Index: It provides the index position of the element in the set.
  • Currentclass: It provides the current class name of the selected element.
switchIt is also an optional parameter. It is a Boolean value which specifies whether the class should be added (true) or removed (false).

Example of jQuery toggleClass() method

Let's take an example to demonstrate the effect of jQuery toggleClass() method.

Test it Now

jQuery toggleClass() example 2

Test it Now

jQuery toggleClass() example 3

Test it Now
Next TopicjQuery width()




Latest Courses