With jQuery toggleClass method, you can add or remove class depending on its presence. If class is present , it will be removed and if class is not present , it will be applied.
classname:Required. It is classname for which you want to toggle class
function(index,currentclass) : Optional .It is function that will be returned with one or more classname to be removed or added.
index : It will provide you index of element in the set.
currentclass: It is current class for selected elements.
State : Optional.If state is true, classname will only be added and if it false, className will be only removed.
1 2 3 |
jQuery.toggleClass( classname [, function(index,currentclass) ] [, state ] ) |
function(index,currentclass) : Optional .It is function that will be returned with one or more classname to be removed or added.
index : It will provide you index of element in the set.
currentclass: It is current class for selected elements.
State : Optional.If state is true, classname will only be added and if it false, className will be only removed.
jQuery toggleClass example:
Lets create html file named jQuerytoggleClass.html as below
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 |
<title>JQuery Toggle to Show/Hide Content</title> <script src="http://code.jquery.com/jquery-2.2.3.min.js"></script> <h2>Jquery toggleClass example</h2> <style> .divClass{ border:3px dotted red; color:red; font-family: arial narrow; } </style> <script type="text/javascript"> $(document).ready(function(){ $("#mybutton").click(function(){ $("div").toggleClass("divClass"); }); }); </script> <button id="mybutton">Click to toggle class</button> <div> Hello world from java2blog!!!! <br> Welcome to JQuery. </div> |
Live demo:
JQuery toggleClass example
Explanation:
- $(document).ready(function() : This function will get called when fully DOM is loaded.
- $(“button”).click(function(event) : This function will get called when “click to toggle class” button is clicked.
- $(“div”).toggleClass(“divClass”): Here we are calling toggleClass for div elements.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.