If you work in web design or development, you likely seek ways to incorporate dynamic effects and interactions. Particularly with images, adding animation on mouseover can captivate users. This article offers a detailed guide on using jQuery’s animate() function to shrink an image on mouseover and restore it to its original size on mouseout.
Example of the Image to be Implemented
First, here’s the image that will expand and contract:
You can consider this as a preview of how it will look on a real website.
CSS for the Image Display Area
The CSS applied to the .clGallery class, where the image is displayed, is crucial. This style definition ensures that the image is centered on a white background. It also includes a cursor setting to indicate that the image is clickable. This CSS is basic, so feel free to customize it to fit your project’s requirements and design.
<style type="text/css">
<!--
.clGallery{
background-color:#FFFFFF;
width:300px;
height:300px;
overflow:hidden;
margin:10px auto;
cursor:pointer;
}
.clTxt{
margin-left:10px;
padding:3px;
}
h2{
font-size:14px;
font-weight:normal;
line-height:1.4em;
}
-->
</style>
JavaScript to Achieve Image Resizing Animation
Here’s the core section that implements the animation using jQuery. First, you need to load jQuery version 1.8. Then, you define the actions for the .clGallery class on mouseover and mouseout. Specifically, the image’s width shrinks to 100px on mouseover and returns to 300px on mouseout.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.clGallery').hover(function(){
$(this).find('img').animate({width:100, marginTop:10, marginLeft:10}, 200);
},function(){
$(this).find('img').animate({width:300, marginTop:0, marginLeft:0},300);
});
});
</script>
HTML Structure for Resizing Animation
Below is the HTML structure displayed in the browser. The img tag under the .clGallery class will be animated. Please also check out the hidden text section.
<div class="clGallery">
<img src="i01.jpg" width="300" alt="">
<div class="clTxt">
<h2>Hidden text here.</h2>
</div>
</div>
Demo Page to Showcase Image Resizing on Mouseover and Mouseout
You can check out the actual behavior on the demo page linked below.
Resizing Image on Mouseover and Mouseout Demo
Conclusion
That’s how to implement a dynamic image resizing effect using jQuery. By incorporating such effects, you can potentially increase the time users spend on your site and encourage greater engagement. We’ll be sharing more techniques and advice to enhance your website’s design and functionality in future articles, so stay tuned!
※ If you use this, please do so at your own risk. Don’t reuse the Google Analytics tag from the demo page.