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.
Suppose you have an HTML button element like this:
You can use jQuery to toggle a class on the content <div> element, when the button is clicked:
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:
With the following jQuery code, clicking the box element will toggle between different classes, creating varied visual effects:
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.
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.
This is a paragraph
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.