Sunday 22 August 2021

Add, remove and toggle css class using jQuery

Hi guys , in this post we will see how to add, remove and toggle css class using jQuery.  As we know that jquery is library of javascript which can be used to do css manipulation. Let's see it practically.
    In this demo, we will add one paragraph element and three buttons one for adding css class, one for removing css class and one for toggling css class.

Add, remove and toggle css class using jQuery

Please follow below steps:-

 1)Open your editor such as visual studio/notepad.

   2)Add html, head, script and body tag.

   3) Add CDN links for jquery .js files in head tag:-            

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>  

4) Add one paragraph element and three buttons one for adding css class, one for removing css class and one for toggling css class.

 <p>This is sample text.</p><br/>

  <button Id="btnAddClass">Add Css Class</button>

  <button Id="btnRemoveClass">Remove Css Class</button>

  <button Id="btnToggleClass">Toggle Css Class</button>

 5) Add css class in style section.

   <style type="text/css">
    .SampleText
        {
          color:red;
          font-size:50px;
        }
    </style>
 6) Add following jquery code in script section.

  <script type="text/javascript">
$(document).ready(function(){
$('#btnAddClass').click(function(){
$('p').addClass('SampleText');
});
$('#btnRemoveClass').click(function(){
$('p').removeClass('SampleText');
});
$('#btnToggleClass').click(function(){
$('p').toggleClass('SampleText');
});
});
</script>

In above code, add document ready function to check whether DOM is fully loaded. Then add three click event handler for three buttons. You can use following method to do css manipulation.
   
    addClass() method is use to add css class to html elements.
    removeClass() method is use to remove css class from html elements.
    toggleClass() method is use to toggle css class to html elements.

Full Code:-

<html>

<head>

<style type="text/css">

.SampleText

{

  color:red;

  font-size:50px;

}

</style>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<script type="text/javascript">

$(document).ready(function(){

$('#btnAddClass').click(function(){

$('p').addClass('SampleText');

});

$('#btnRemoveClass').click(function(){

$('p').removeClass('SampleText');

});

$('#btnToggleClass').click(function(){

$('p').toggleClass('SampleText');

        });

});

</script>

</head>

<body>

  <p>This is sample text.</p><br/>

  <button Id="btnAddClass">Add Css Class</button>

  <button Id="btnRemoveClass">Remove Css Class</button>

  <button Id="btnToggleClass">Toggle Css Class</button>

</body>

</html>

No comments:

Post a Comment