How to use switchClass and toggleClass in jQuery

In this tutorial, I talked about a two jQuery method – switchClass() and toggleClass(). As their name suggest its related to classes, and they both are used for changing or replacing the class from an element.

When did it use?

You can use them to show the change of state of the element according to the condition, toggling classes within the elements or may be in some other cases.

For example – You have an Education website where students are assigned to courses. When student reading lessons there is an option for setting Lesson state to read or Unread. For showing the change of state you have created two classes one for unread and another for read which you want to use according to the state of a lesson.

In this kind of case you can either use removeClass() and addClass() for removing one class and add another class to an element or do it using a single method (switchClass or toggleClass).

Within tutorial, I am creating a small example for that where I use switchClass() method and various other 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, in other words, it replaces one class with another. For using it you need to add jQuery UI library to your 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 example creating a post list which is in unread state and when Read button gets clicked then changing Post class.

HTML

Created a 3 post lists structure and add post-unread class to them and also have a Read Button.

<!doctype html>
<html>
 <head>
 <title>How to use switchClass and toggleClass in jQuery</title>
 <link href='style.css' rel='stylesheet' type='text/css'>
 <link href='jquery-ui.css' rel='stylesheet' type='text/css'>
 <script src='jquery-1.12.0.min.js' type='text/javascript'></script>
 <script src='jquery-ui.js' type='text/javascript'></script>
 <script src='script.js' type='text/javascript'></script>
 
 </head>
 <body>
 <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>
 </body>
</html>

jQuery

When the button gets clicked then get post_id from it by splitting its id, and using this post_id to check that it has ‘post-unread’ class or not.

For this using hasClass() method it takes a class name and returns true if its find that class in an element otherwise false.

If it returns true then switch that post_id class from post-unread to post-read and changing Button text to Unread otherwise switch post-read class to post-unread and setting Button Text to 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;
}

When you run the program it gives the following output –

# Example 2 – Using duration with swichClass

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

HTML

Within HTML created a dropdown for changing duration value and created two divs with class red and blue.

<!doctype html>
<html>
 <head>
  <title>How to use switchClass and toggleClass in jQuery</title>
  <link href='style.css' rel='stylesheet' type='text/css'>
  <script src='jquery-1.12.0.min.js' type='text/javascript'></script>
  <script src='script.js' type='text/javascript'></script>
 </head>
 <body>
  <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>
 </body>
</html>

jQuery

Defined click event on <div> with id div1 and div2.

Take out selected duration value from dropdown and storing it to duration variable. If duration value is not equal to slow and fast then converting duration value to a number using Number() method.

Using hasClass for finding red class on clicked <div> element. If it has then replaced red class with blue and also passing third parameter duration in switchClass() method for setting a little delay in animation.

If the <div> has didn’t red class then changing blue class to red.

$(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;
}

When you run the program it gives the following output –


 

2. toggleClass

It toggles classes in an element and for using this you don’t need to include jQuery UI library within your web page. It works only by including jQuery 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

<!doctype html>
<html>
 <head>
 <title>How to use switchClass and toggleClass in jQuery</title>
 <link href='style.css' rel='stylesheet' type='text/css'>
 <script src='jquery-1.12.0.min.js' type='text/javascript'></script>
 <script src='script.js' type='text/javascript'></script>
 </head>
 <body>
  <div class='container'>
   <p class='normal'>Using toggleClass to change class of a paragraph</p>
   <button id='toggle'>Toggle</button>
  </div>
 </body>
</html>

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 of the program –

# 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. This done using jQuery.

<!doctype html>
<html>
 <head>
 <title>How to use switchClass and toggleClass in jQuery</title>
 <link href='style.css' rel='stylesheet' type='text/css'>
 <script src='jquery-1.12.0.min.js' type='text/javascript'></script>
 <script src='script.js' type='text/javascript'></script>
 </head>
 <body>
 <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>
 </body>
</html>

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 of the program –


 

3. Conclusion

switchClass() and toggleClass() method makes your changing classes from a element very simple.

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

If you want to read in more detail you can refer to following links –

 

Spread the love

Related Post

Be First to Comment

Leave a Reply

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