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.
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%" />
</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>
By switching the class names the icon size is changed from smaller to larger and further 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>