Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   
   HTML   
   CSS   
   JAVA SCRIPT   
   JQUERY   




CSS METHODS - toggleClass()


The toggleClass() method in JQuery is a combination of addClass() and removeClass() method. It toggles between addClass() and removeClass().


Example :



<html>
    <head>
    	<title> My First Programme </title>
  	</head>

	<style>
    	.myClass {
        	background-color: violet;
        }
    </style>
    
  	<body>
    	<h1> JQuery </h1>
    	<p class = "myClass">New Code</p>
    	
    	<button> Click Here </button>
    	
      	<script src = "https://cdnjs.cloudflare.com/ajax/libs/JQUERY/3.3.1/jquery.min.js"> </script>
	  
      	<script>
      
      		$('button').click( function() {
				$('p').toggleClass("myClass");
			});
			
      	</script>      
   </body>
</html>


Output :




So, in the above code, we have a <p> element, with the class 'myClass',


<p class = "myClass">New Code</p>

Which is defined in a CSS style property,


<style>
	.myClass {
		background-color: violet;
	}
</style>

Now, all we are going to do is, remove the class on click and add the class again using the 'toggleClass()' method.


In other words, we are going to toggle between addClass() and removeClass().


And we have achieved it using the JQuery statement,


$('button').click( function() {
	$('p').toggleClass("myClass");
});

All we are doing is, using the 'toggleClass()' method on the <p> element, to remove the class 'myClass' from the <p> element. And add it back using the same click.


$('p').toggleClass("myClass");