jQuery toggleClass()

The jQuery toggleClass() method is a versatile tool for toggling the presence of a CSS class on selected HTML elements. It allows you to dynamically alternate between adding and removing a class, providing a straightforward way to implement interactive behaviors.

Basic Toggle

Suppose you have an HTML button element like this:

<button id="toggleButton">Toggle Highlight</button> <div id="content">This is the content to highlight.</div>

You can use jQuery to toggle a class on the content <div> element, when the button is clicked:

$("#toggleButton").click(function() { $("#content").toggleClass("highlight"); });

In this scenario, clicking the button will alternately add and remove the "highlight" class from the content <div>, resulting in dynamic styling changes.

Toggle with Multiple Classes

The toggleClass() method can also accept multiple classes, allowing for more complex toggling scenarios. Consider the following HTML structure:

<div id="box">This is a box</div>

With the following jQuery code, clicking the box element will toggle between different classes, creating varied visual effects:

$("#box").click(function() { $(this).toggleClass("large red"); });

In this case, clicking the box will toggle between the "large" and "red" classes, altering both the size and color of the box.

jQuery toggleClass() Example

The following code create a toggle effect in your webpage. This method takes one or more class names as its parameter.

$("p").toggleClass("highlight1"); $("div").toggleClass("highlight2");
<p class="highlight1">This is a paragraph</p> <div class="highlight2"> This is a Div</div>

The above code would remove a class with one click and in second click it would again add the same class. As with the other methods, multiple class names can be provided, separated by a space.

run this source code Browser View

This is a paragraph

This is a Div

Full Source
<html> <head> <title>jQuery</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("p").toggleClass("highlight1"); $("div").toggleClass("highlight2"); }); }); </script> <style> .highlight1 { background:red; } .highlight2 { background:green; } </style> </head> <body> <p class="highlight1">This is a paragraph</p> <div class="highlight2"> This is a Div</div> <br> <button>Click me</button> </body> </html>

Conclusion

The toggleClass() method streamlines the process of creating interactive and dynamic user interfaces, allowing for smooth transitions between different states without needing to manage class addition and removal manually.