Switch CSS Class Using jQuery

by Vincy. Last modified on July 12th, 2022.

In this post, we are going to switch the CSS class using jQuery. In a previous post, we have seen how to switch CSS file based on the screen size to make page responsive.

We have an example showing an image icon which is smaller on page load. And then we are switching the class attribute of this icon and changing its size using jQuery.

View Demo

Switching Class Name using jQuery

This HTML form shows a smaller image icon with the class name small-icon.


<div class="image-content">
	<button id="switch">Switch Class</button> 
	<div  class="small-icon">
	  <img src="image.png" width="100%" />

This class attribute is changed on the button click event. jQuery switchClass function is used to change the class attribute. The script is,

  $(document).ready(function() {
      $(".small-icon").switchClass("small-icon", "large-icon", 500);
      $(".large-icon").switchClass("large-icon", "extra-large-icon", 500);
	  $(".extra-large-icon").switchClass("extra-large-icon", "small-icon", 500);

By switching the class names the icon size is changed from smaller to larger and further to extra-larger size. The styles are,

  .image-content{width: 200px;border: #D2CCCC 1px solid;padding: 5px 40px;height: 280px;border-radius: 4px;box-shadow: 0px 2px 5px rgba(0, 0, 0, 0.25);}
	#switch {padding: 10px 20px;margin: 15px 0px;border-radius: 4px;border: 0;background: #7A7B7B;color: #FFF;}

View DemoDownload

Leave a Reply

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

↑ Back to Top

Share this page