Javascript examples for jQuery Method and Property:toggleClass
The toggleClass() method toggles between adding and removing one or more class names from the selected elements.
$(selector).toggleClass(classname,function(index,currentclass),switch);
Parameter | Require | Description |
---|---|---|
classname | Required. | one or more class names to add or remove. |
function(index,currentclass) | Optional. | function that returns one or more class names to add/remove |
switch | Optional. | A Boolean value specifying if the class should only be added (true), or only be removed (false) |
To specify several classes, separate the class names with a space
The following code shows how to Toggle between adding and removing the "main" class name for all <p> elements:
<!DOCTYPE html> <html> <head> <style> .main {/* www. j ava 2 s .co m*/ font-size: 120%; color: red; } </style> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("p").toggleClass("main"); }); }); </script> </head> <body> <button>Toggle class "main" for p elements</button> <p>This is a paragraph.</p> <p>This is another paragraph.</p> <p><b>Note:</b> Click the button more than once to see the toggle effect.</p> </body> </html>