How to change class jquery – toggleClass jQuery

How to change class jquery – toggleClass jQuery

In the last post we learnt how to add a class by jquery. Now we will add a class on first click, then on the second we will remove the class.

To accomplish this the first we have to do load up the jquery library, we learnt this in the addClass jquery tutorial then we will do the same thing create a new file named script.js and we will add the following block of code.

jQuery:

 

jQuery(function(){
   jQuery('.trigger').on('click', function(){
      jQuery('body').toggleClass('selected');
    });
});

 

In this script we check for the document if it's ready, then on first click we add class "selected" on the body, then on the second click if the body already has "selected" class the function "toggleClass" will remove the class and so on.

 

HTML:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="trigger"></div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</html>

 

Leave a Reply

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