How to use switchClass and toggleClass in jQuery

The switchClass and toggleClass are jQuery methods that are used to swap classes from the element.

You can use these methods to change of state of the element according to the condition, toggling classes within the elements or maybe in some other cases.

In this tutorial, I am creating various examples to explain both methods.

How to use switchClass and toggleClass in jQuery


Contents

  1. switchClass
  2. toggleClass
  3. Conclusion

 

1. switchClass

It is used to switch class from an element. For using it you need to add jQuery UI library with jQuery on the page.

You can download it from it Offical website. Either you can use

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">

and

<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>

Syntax –

switchClass(removeClassName, addClassName, [,duration])

Parameters –

  • removeClassName – It is the name of a class which you want to replace.
  • addClassName – It is the name of a class from which you want to replace.
  • duration – It is an optional parameter from there you can set how long an animation took place. i.e, – the value may be ‘slow’,’fast’, 400, 2000,etc. Its default value is 400.

# Example 1 – Switch one class with another

Within the example creating a post list which is in unread state and when Read button gets clicked then change the Post class.

HTML

Created a 3 post lists structure and add class = 'post-unread'. Also, a Read Button to switch class using jQuery.

 <div class='container'>
   <div class='posts-list'>
 
    <div class='post-unread' id='post_1'>
     <h1><a href='http://makitweb.com/schedule-posts-wordpress-without-plugin/'>How to Schedule Posts in WordPress without plugin</a></h1>
     <p>Schedule post in WordPress is its inbuilt feature, you don’t need any extra plugin for it, which is great. and if you want the more extra feature then you go…</p>
     <button class='read' id='read_1'>Read</button>
    </div>
 
    <div class='post-unread' id='post_2'>
     <h1><a href='http://makitweb.com/search-value-within-comma-separated-values-mysql/'>Search for value within a comma separated values in MySQL</a></h1>
     <p>In this tutorial, I will show you How to you can search a value within comma separated column in MySQL table. I will explain about FIND_IN_SET function and difference in…</p>
     <button class='read' id='read_2'>Read</button>
    </div>
 
    <div class='post-unread' id='post_3'>
     <h1><a href='http://makitweb.com/how-to-check-and-uncheck-all-using-jquery-and-javascript/'>How to Check and uncheck all using jQuery and JavaScript</a></h1>
     <p>In this short tutorial, I will show you How you can check or uncheck all checkboxes and list box options using jQuery and JavaScript. I use them many times within…</p>
     <button class='read' id='read_3'>Read</button>
    </div>
 
  </div>
 
 </div>

jQuery

When Read button gets clicked then split the button id to get the post id.

Check the post_id element has class='post-unread' or not. If a class is present on the element then switch the post-unread class with post-read and change button text to 'UnRead'.

Similarly, if class not present then switch post-read class with post-unread and change button text with 'Read'.

$(document).ready(function(){
 $(".read").click(function(){
    var id = this.id;
    var split_id = id.split('_');
    var post_id = 'post_'+split_id[1];
 
    // Checking class using hasClass 
    if($('#'+post_id).hasClass('post-unread')){
 
       // Switch class from post-unread to post-read
       $('#'+post_id).switchClass("post-unread","post-read");
       $(this).text('UnRead'); // Changing Button Text
    }else{
       // Switch class from post-read to post-unread
       $('#'+post_id).switchClass("post-read","post-unread");
       $(this).text('Read'); // Changing Button Text
    } 
 
 });
});

CSS

.posts-list h1{
 font-weight: normal;
 letter-spacing: 1px;
}
.posts-list h1 a{
 text-decoration: none;
 color: white;
}
.posts-list p{
 line-height: 20px;
 text-align: justify;
}
.post-unread{
 background-color: #32cbb4;
 padding: 5px;
 border-radius: 3px;
 margin-bottom: 15px;
 color: white; 
}

.post-read{
 background-color: #f7c282;
 padding: 5px;
 border-radius: 3px;
 margin-bottom: 15px;
 color: white; 
}
.read{
 border-radius: 3px;
 background-color: #ff7373;
 color: white;
 padding: 5px 15px;
 font-size: 16px;
 letter-spacing: 1px;
 display: inline-block;
 border: 0;
}

.read:hover{
 cursor: pointer;
}

Output –


# Example 2 – Using duration with swichClass

In the second example, using duration with switchClass() method.

HTML

Create a drop-down for changing duration value and created two divs with red and blue class.

<div class='container'>
    Set Duration : <select id='duration'>
     <option value='slow' selected>slow</option>
     <option value='fast'>fast</option>
     <option value='400'>400</option>
     <option value='800'>800</option>
     <option value='1200'>1200</option>
     <option value='20000'>20000</option>
    </select><br/>
    <div class='red' id='div1'></div>
    <div class='blue' id='div2'></div>
  </div>

jQuery

Define click event on the <div id='div1'> and <div id='div2'> containers.

When it is gets triggered then get the duration from the drop-down and use the value in switchClass() method.

$(document).ready(function(){
 
 $('#div1,#div2').click(function(){
    var duration = $('#duration option:selected').val();
    if(duration !='slow' && duration !='fast'){
      duration = Number(duration);
    }
 
    if($(this).hasClass('red')){
      $(this).switchClass("red","blue",duration);
    }else{
      $(this).switchClass("blue","red",duration);
    }
 
 });
 
});

CSS

.red{
 background-color: red;
 margin-left: 10px;
 width: 120px;
 height: 120px;
 float: left;
 margin-top: 10px;
}
.blue{
 background-color: blue;
 margin-left: 10px;
 width: 120px;
 height: 120px;
 float: left;
 margin-top: 10px;
}

Output –


 

2. toggleClass

It toggles classes in an element and for using this you don’t need to include jQuery UI library.

What you can do with it –

  • toggle classes
  • add class
  • remove class

Syntax –

toggleClass(className[,state])

Parameter –

  • className – Class names that to be toggled. Multiple classes are separate by space.
  • state – It is an optional parameter and it takes Boolean value. If you pass true then it adds class to the element and if is false then it removes the specified class from the element.

# Example 1 – toggle class of an element

In this example, using the toggleClass method to toggle class of a paragraph element.

HTML

<div class='container'>
   <p class='normal'>Using toggleClass to change class of a paragraph</p>
   <button id='toggle'>Toggle</button>
</div>

jQuery

Toggle <p> element class when toggle button gets clicked.

$(document).ready(function(){

 $("#toggle").click(function(){
   $('p').toggleClass('normal bigger');
 });

});

CSS

.normal{
 font-size: 15px;
 line-height: 20px;
 color: blueviolet;
}

.bigger{
 font-size: 25px;
 color: forestgreen;
}

Output –

# Example 2 – Using with state

I am using the same example as above but added one more button and passing the second parameter to toggleClass in jQuery.

HTML

Added one paragraph and two buttons for add and remove the class from paragraph when gets clicked.

<div class='container'>
   <p class='normal'>Using toggleClass to change class of a paragraph</p>
   <button id='toggle1'>Add class</button>&nbsp;<button id='toggle2'>Remove class</button>
</div>

jQuery

When the first button gets clicked then passing true as the second parameter in toggleClass. This add bigger class to the <p> element.

Same as first but passing false in toggleClass when the second button gets clicked. This remove bigger class from <p> element if it has.

$(document).ready(function(){
 $("#toggle1").click(function(){
   // It add class bigger to paragraph
   $('p').toggleClass('bigger',true);
 });
 
 $("#toggle2").click(function(){
   // It remove class bigger to paragraph
   $('p').toggleClass('bigger',false);
 });
});

Output –


 

3. Conclusion

For using switchClass() method you need to include jQuery UI library within your web page and for toggleClass() it is not required.

You can read more about it from here –

If you like this post then don’t forget to share.

Related Post

Spread the love

Be First to Comment

Leave a Reply

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