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.
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

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?

Leave a Reply

Your email address will not be published. Required fields are marked *