jquery
  1. jquery-toggleclass

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:

<!DOCTYPE html>
<html>
<head>
    <title>JQuery toggleClass() Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        .active {
            background-color: #ff6666;
        }
    </style>
</head>
<body>
    <button>Toggle Class</button>
    <div>This is a div element</div>

    <script>
        $("button").click(function(){
            $("div").toggleClass("active");
        });
    </script>
</body>
</html>
Try Playground

In this example, a button and a div element are created. The active class is defined in the style section, which sets the background color of the element to red. When the button is clicked, the toggleClass() method is called on the div element, which toggles the active class on and off.

Summary

JQuery toggleClass() is a powerful tool that simplifies dynamic web page design. It's often used to add or remove classes when events occur, such as button clicks or hover events. With its simple syntax and many options, toggleClass() is a valuable feature of the JQuery library.

Published on: