jQuery toggleClass()

The jQuery toggleClass() method adds or removes one or more classes of the selected element. If the class name is already added, toggleclass() method removes it and if the class name was removed earlier, it adds the class name, creating a toggle effect.

Syntax:

$(selector).toggleClass(classname,function(index,currentclass),switch)

Classname:

  • Classname is a compulsory parameter of the jQuery toggleClass() method, as it specifies the class names to add or remove.

Function:

  • It is an optional parameter.
  • The function parameter is used to return the class names to be added or removed.

Index:

  • The index is an argument passed within the function.
  • It is used to give an index position to an element in the set.

Currentclass:

  • This parameter returns the current class name of the selected element.

Switch:

  • Switch is also an optional parameter, which specifies whether the class should be added or removed.

Example:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").toggleClass("main");
});
});
</script>
<style>
.main {
font-size: 20
color: red;
}
</style>
</head>
<body>
<button>Toggle class</button>
<p>Hello!</p>
</body>
</html>
Please follow and like us:
Content Protection by DMCA.com