JQuery toggleClass()
JQuery toggleClass()
is a useful method that allows you to add or remove a CSS class from an element on a web page. The method toggles the class on and off based on the element's current state.
Syntax
Here's the syntax for JQuery toggleClass()
:
$(selector).toggleClass(classname, switch)
selector
: Required. The HTML element(s) to toggle the class on.classname
: Required. The name of the class to be toggled.switch
: Optional. A boolean value that determines whether to add (true
) or remove (false
) the class.
Use
JQuery toggleClass()
is often used to add or remove classes when an event occurs, such as when a user clicks a button or hovers over an element. It's a powerful tool for dynamic web page design and can help simplify your code by taking care of the class changes for you.
Example
Here's an example of using JQuery toggleClass()
to add and remove a class when a user clicks on a button: