Switch CSS Class Using jQuery

In this post, we will switch the CSS class using jQuery. In a previous post, we saw how to switch CSS files based on the screen size to make the page responsive.

We have an example showing an image icon that is smaller on page load. And then, we switch the class attribute of this icon and change 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.

switch-css-class-using-jquery

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

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

<script>
  $(document).ready(function() {
    $("#switch").click(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);
    });
  });
</script>

Switching the class names changes the icon size from smaller to more significant and to extra-larger size. The styles are,

<style>
  .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;}
  .small-icon{width:50px;}
  .large-icon{width:100px;}
  .extra-large-icon{width:200px;}
</style>

View DemoDownload

Photo of Vincy, PHP developer
Written by Vincy Last updated: July 6, 2023
I'm a PHP developer with 20+ years of experience and a Master's degree in Computer Science. I build and improve production PHP systems for eCommerce, payments, webhooks, and integrations, including legacy upgrades (PHP 5/7 to PHP 8.x).

Leave a Reply

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

Explore topics
Need PHP help?