jQuery toggleClass() Method

jQuery | toggleClass() Method: Learn about the jQuery toggleClass() Method with its usages, syntax, and examples.
Submitted by Pratishtha Saxena, on October 16, 2022

toggleClass() Method

Generally, a CSS class is declared when the HTML of the page is written down. At that time only the classes are specified for the elements. During that time a lot of CSS classes are declared for an element. There might be a situation when you want to remove and add a class based on some dynamic events. This can be achieved by using jQuery's method – toggleClass().

The toggleClass() method in jQuery helps to toggle between the classes. This means that if the class specified in this method is not contained by the selected element, then it will add the class to it. On the other hand, if the class is present then this method will remove it from the element. This way it switches between the respective class.

toggleClass() Method Syntax

$('selector').toggleClass('className',switch);

Along with the class name as its parameter, it also takes an optional parameter – switch. Switch can be defined as true or false. This follows only one event, i.e., it only allows you to either add or remove the specified class. By default, the switch is always set as – true.

Now, the following example explains the implementation of the toggleClass() method in jQuery. When the button is clicked, it triggers the method which further switches the classes for the element.

jQuery toggleClass() Method Example

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <title>Document</title>
    <style>
      .green{
      font-size: larger;
      font-weight: bolder;
      color: green;
      }
      .blue{
      font-size: larger;
      font-weight: bolder;
      color:darkblue;
      }
    </style>
  </head>
  
  <body>
    <h2>jQuery - ToggleClass</h2>
    <p>Click the button to toggle between the classes.</p>
    <button>ToggleClass</button>
    <hr>
    <div>This is SENTENCE ONE</div>
    <br>
    <div>This is SENCTENCE TWO</div>
    <p class="blue">This is SENTENCE THREE</p>
    <hr>
    <h3 style="color:crimson ;"></h3>
  </body>
  
  <script type="text/javascript">
    $(document).ready(function(){
        $('button').click(function(){
            $('div').toggleClass('green');       
        });
    });
  </script>
</html>

Output:

Example 1: jQuery toggleClass() Method


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.