Toggle Class in jQuery


Class toggling using jQuery can bring life to your website. It can be used at various places like toggling the menu bar, toggling the dark mode, etc.

Toggling class means manipulating HTML elements by adding or removing classes from them. It's extensively used for creating interactive web experiences, animations, and responsive designs.

In this tutorial, you will learn how to toggle class and anything around it.

    Table of Contents

  1. jQuery toggleClass() Method
  2. Toggle Class based on Conditions
  3. Toggle Multiple Classes
  4. Toggle Class with Delay
  5. Conclusion

1. jQuery toggleClass() Method

The toggleClass() is a special method in jQuery that is used to toggle the class of an element, i.e., it adds the class if it is not present and removes the class if it is already present.

To toggle the class of an element, you need to pass the class name as an argument to the toggleClass() method.

Example

$("#elementID").click(function() {
  // Toggle the class "active" on the element with id "elementID"
  $(this).toggleClass("active");
});

2. Toggle Class based on Conditions

For real life use cases, you can toggle the class based on some conditions.

Here is an example that toggles the class based on the current time of the day.

Example

$("#elementID").click(function() {
  // Get the current hour of the day
  let hour = new Date().getHours();

  // If the hour is less than 12, add the class "day" to the element
  if (hour < 12) {
    $(this).addClass("day");
  } else {
    // Otherwise, remove the class "day" from the element
    $(this).removeClass("day");
  }
});

3. Toggle Multiple Classes

The toggleClass() method allows you to toggle multiple classes at once.

To toggle multiple classes, you need to pass the class names as arguments to the toggleClass() method.

Example

$("#elementID").click(function() {
  // Toggle the classes "red" and "big" on the element with id "elementID"
  $(this).toggleClass("red big");
});

4. Toggle Class with Delay

There are times when you want to toggle the class after a certain delay. For example, you may want to toggle the class after 2 seconds.

For this, you can use the setTimeout() method with the toggleClass() method.

Example

$("#elementID").click(function() {
  // Toggle the class "active" on the element with id "elementID" after 2 seconds
  setTimeout(() => {
    $(this).toggleClass("active");
  }, 2000);
});

Conclusion

Mastering class toggling in jQuery provides extensive control over element behavior, styling, and interaction. These methods empower you to create dynamic and engaging web applications.

Experiment with these techniques to enhance user experiences and add interactivity to your projects.

Happy Coding!😇