jQuery ToggleClass and SwitchClass: Simplifying Class Manipulation

When it comes to jQuery, two powerful functions—toggleClass and switchClass—empower developers with seamless class manipulation capabilities. Whether you want to toggle classes on and off or smoothly switch between different classes, these functions are essential tools in your web development.

In this article, we will delve into the world of toggleClass and switchClass in jQuery, providing comprehensive guidance on their usage. From basic syntax to practical examples, you’ll learn how to implement dynamic class changes effortlessly. Discover how toggleClass and switchClass can elevate your web development projects, making them interactive and visually appealing.

jQuery ToggleClass and SwitchClass: Simplifying Class Manipulation


Table of Content

  1. jQuery UI switchClass
  2. jQuery toggleClass
  3. Conclusion

1. jQuery UI switchClass

The switchClass function provides a seamless way to switch between classes on selected elements. It allows for smooth transitions and dynamic changes in the appearance or behavior of elements.

To use it you need to add jQuery UI library with jQuery on the page. You can download it from its Offical website or you can use CDN –

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

and

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

Syntax –

switchClass(removeClassName, addClassName, [,duration])

Parameters –

  • removeClassName – It is the name of a class that 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 create a post list that is in an unread state and when the 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'>
              <h2><a href='https://makitweb.com/schedule-posts-wordpress-without-plugin/'>How to Schedule Posts in WordPress without plugin</a></h2>
              <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'>
              <h2><a href='https://makitweb.com/search-value-within-comma-separated-values-mysql/'>Search for value within a comma separated values in MySQL</a></h2>
              <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'>
              <h2><a href='https://makitweb.com/how-to-check-and-uncheck-all-using-jquery-and-javascript/'>How to Check and uncheck all using jQuery and JavaScript</a></h2>
              <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 the 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 the class is 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 h2{
    font-weight: normal;
    letter-spacing: 1px;
}
.posts-list h2 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;
}

View Demo


# Example 2 – Using duration with switchClass

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

HTML

Create a drop-down for changing duration value and create 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 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;
}

View Demo


2. jQuery toggleClass

The toggleClass function in jQuery is a powerful tool for dynamically adding or removing classes from selected elements. By toggling the presence of a class, you can create interactive effects and switch between different styles effortlessly.

It does not require a 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 separated by space.
  • state – It is an optional parameter and it takes a 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 the 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;
}

View Demo


# 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 the paragraph when it 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);
    });
});

View Demo


3. Conclusion

ToggleClass and switchClass in jQuery offer powerful class manipulation capabilities, enabling dynamic and visually appealing web experiences. With toggleClass, you can add, remove, and toggle classes based on user interactions. SwitchClass facilitates smooth class transitions, adding visual effects and animations.

These functions enhance interactivity, making buttons, menus, galleries, and forms come alive. Mastering toggleClass and switchClass empowers you to create captivating web applications that engage and delight users.

Embrace these functions, unlock their potential, and elevate your web development skills.

If you found this tutorial helpful then don't forget to share.

Leave a Comment