How To Toggle Class In Jquery

In this blog post, we will learn how to toggle a class using jQuery. Toggling a class means adding the class if it’s not present and removing it if it’s already present. This can be useful for changing the appearance or behavior of elements on the page without needing to refresh the page or use more complex JavaScript functions.

Prerequisites

Before we dive into the code, make sure you have the following:

  • jQuery library included in your project. You can either download it from the official jQuery website or include it through a CDN like Google or Microsoft.

Here’s an example of how to include the jQuery library through Google CDN:

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    

Using .toggleClass() method

jQuery provides a method called .toggleClass() which allows you to toggle a class on the selected elements. The basic syntax for the method is:

    $(selector).toggleClass(className);
    

Where selector is the element(s) you want to toggle the class on, and className is the class name you want to toggle.

Example 1: Toggle a class on a button click

Let’s say we have a button and a paragraph, and we want to toggle the class “highlighted” on the paragraph when the button is clicked. Here’s how we can do it:

    <button id="toggle-btn">Toggle Class</button>
    <p id="paragraph">This is a sample paragraph.</p>

    <script>
    $(document).ready(function() {
        $("#toggle-btn").click(function() {
            $("#paragraph").toggleClass("highlighted");
        });
    });
    </script>
    

In this example, we have selected the button with the ID “toggle-btn” and attached a click event to it. Inside the click event, we are selecting the paragraph with the ID “paragraph” and toggling the class “highlighted” using the .toggleClass() method.

Example 2: Toggle multiple classes

You can also toggle multiple classes at once by passing them as a space-separated string in the .toggleClass() method. Here’s an example:

    <button id="toggle-btn">Toggle Classes</button>
    <div id="box">This is a sample box.</div>

    <script>
    $(document).ready(function() {
        $("#toggle-btn").click(function() {
            $("#box").toggleClass("bordered rounded");
        });
    });
    </script>
    

In this example, we are toggling both “bordered” and “rounded” classes on the div with the ID “box” when the button with the ID “toggle-btn” is clicked.

Conclusion

Now you know how to toggle a class in jQuery using the .toggleClass() method. This method is very useful for changing the appearance or behavior of elements on your web page, and it’s very easy to use. Try it in your next project and see the difference it can make!