Description:
The jQuery toggleCLass() method is used to add or remove one or more classes from the selected elements. ย In simple, the toggleClass() method checks each element for the specified class names. ย If the class name is already presented for the selected element then it will remove else it will add the class.
Syntax
$(selector).toggleClass(classname,function(index,currentclass),state)
classNameย | It specify One or more class names to add/remove from the selected set. More than one class name will be separated by the empty space |
function(index,currentclass) | A function that returns one or more class names to remove index : Returns the index position of the matched element currentclass : Returns the current class name of the matched element |
state | It specity the boolean value for the class should be added or removed. add: true , ย remove: false |
Example:ย
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
<html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script> <style> .CustomClass { border:2px soli<html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script> <style> .defaultClass { border: 5px solid #eed5b7; padding: 10px; width: 400px; height: 100px; background-color: #eed5b7; } .CustomClass { border: 5px solid #4cff00; font-size: 25px; background-color: #4cff00 !important; } </style> <script type="text/javascript"> $(document).ready(function () { $('.btnClass').click(function () { $('#divCssBoard').toggleClass("CustomClass"); }) }); </script> </head> <body> <button class="btnClass" id="addMethod">Toggle CSS Class</button><br/><br /> <div id=divCssBoard class="defaultClass"> Welcome to dotnet-helpers.com </div> </body> </html> |
Output:ย
As per code, ย on clicking of “Toggle CSS Class” button, the toggleClass method will verifyย the selected div with the “CustomClass”, if its notย present then it will addย the class else it will remove the class as shown below.
Leave A Comment