jQuery toggleClass example

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.
jQuery.toggleClass( classname [, function(index,currentclass) ] [, state ] )
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.

jQuery toggleClass example: 

Lets create html file named jQuerytoggleClass.html as below
  <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>
        border:3px dotted red;
        font-family: arial narrow;
<script type="text/javascript">
  <button id="mybutton">Click to toggle class</button>
 Hello world from java2blog!!!!
 Welcome to JQuery.
Live demo:
JQuery toggleClass example
  • $(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. 

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus


Java tutorial for beginners Copyright © 2012