Introduction:

In this article we will explain what is toggleCLass() method in jQuery or how to once click add class name from html selected elements or how to remove class name once clicking from selected elements in jQuery with example.

Description:

The jQuery toggleCLass() method is used to add or remove one or more classes from the html selected elements. This method toggles between adding and removing one or more class name. It checks each element for the specified class names. If the class name is already set, it removes and if the class name is not exists, it adds.

Example of jQuery toggleClass() method

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Jquery Tutorials</title>
    <script src="Scripts/jquery-1.8.2.min.js"></script>
</head>
<body>
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                $("div").toggleClass("Myclass");
            });
        });
    </script>   
 
        <div class="div"></div>
        <div class="div"></div>
   
 
    <button>Click here to add/remove class</button>
    <style>
        .div {
            height: 100px;
            width: 200px;
            background: #77c4fe;
            margin-bottom: 10px;           
        }
 
        .Myclass {
            background: #f66262;
        }
    </style>
</body>
</html>

 

Output:

Use jQuery toggleClass()

When we click once on button “Myclass” class name adds in div and click once again “Myclass” class name removed fron div. like shown as below image:

Use jQuery toggleClass()

I hope it will help to you.

0 comments


Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

you may also like