What Does the jQuery toggleClass Method Do
The jQuery toggleClass() method dynamically adds or
removes one or more CSS classes from selected HTML elements depending on
whether the class is currently present. If an element already possesses
the specified class, toggleClass() removes it; if the
element lacks the class, the method adds it. This article explains how
the method works, its syntax options, and common practical applications
for dynamic web styling.
How toggleClass() Works
The primary purpose of toggleClass() is to eliminate the
need for manual hasClass(), addClass(), and
removeClass() conditional checks. Instead of writing
conditional statements to determine an element's current state, a single
line of code switches the state automatically.
Basic Syntax
The most common syntax takes one or more class names as a string:
$(selector).toggleClass(className);- selector: The HTML element or group of elements you want to target.
- className: One or more class names separated by spaces.
For example, to toggle a highlight effect on a button click:
$("button").click(function () {
$("#contentBox").toggleClass("highlight");
});If #contentBox does not have the highlight
class, clicking the button applies it. Clicking the button a second time
removes it.
Using the Boolean State Parameter
The toggleClass() method accepts an optional second
argument: a boolean switch that determines whether the class should be
strictly added or removed:
$(selector).toggleClass(className, state);- state = true: Forces the class to be added,
behaving identically to
.addClass(). - state = false: Forces the class to be removed,
behaving identically to
.removeClass().
This is useful when toggling styles based on conditional expressions, such as tracking scroll positions or form validation states:
// Adds 'scrolled' if scroll position is greater than 100px; removes it otherwise
$(window).scroll(function () {
$("nav").toggleClass("scrolled", $(this).scrollTop() > 100);
});Toggling Multiple Classes
Multiple classes can be toggled simultaneously by separating each class name with a space:
$("#card").toggleClass("active visible expanded");Each listed class is evaluated individually on the element.
Using a Function
You can also pass a function that returns class names to toggle. This function takes the zero-based index of the element and the element's existing class name as arguments:
$("li").toggleClass(function (index, currentClassName) {
if ($(this).parent().is(".special-list")) {
return "highlight";
}
return "";
});Common Use Cases
- Navigation Menus: Expanding and collapsing mobile navigation menus on click.
- Dark Mode Toggles: Switching the
bodyclass between light and dark themes. - Accordion Components: Hiding and showing accordion panels.
- Interactive UI States: Updating active or focused states on tabs, buttons, and cards.