Image zoom on hover can be really a nice feature. Specially when you have a shopping cart website or a blog, image zoom feature add some stars in user experience.
I know there are lots of “jQuery zoom image on hover” plugins available on the internet. But I don’t think so to use jquery plugin for that because it is very simple to do. So in this tutorial I am going to show you how to zoom image on hover using jquery.
HTML:
1 2 3 4 5 6 7 8 9 10 11 12 |
<div class="img-container"> <img src="images/Koala.jpg" width="300"> </div> <div class="img-container"> <img src="images/Lighthouse.jpg" width="300"> </div> <div class="img-container"> <img src="images/Penguins.jpg" width="300"> </div> |
CSS:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
.img-container{ border:1px solid #eeeeee; overflow:hidden; width:300px; height:220px; float:left; } img{ opacity:1; } |
I used overflow:hidden;
property in .img-container
just to wrap images with in the border. Rests of the properties are for design purpose.
jQuery:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script> $(document).ready(function(){ $("img").hover(function(){ $(this).animate({width:'350px',marginLeft:'-10%',marginTop:'-10%'}); $(this).css("opacity","0.7"); }, function(){ $(this).animate({width:'300px',marginLeft:'0px',marginTop:'0px'}); $(this).css("opacity","1"); }); }); </script> |
I used $("img")
selector which means this hover function will apply on all images of a page. jQuery hover() function has 2 parameters. First is for mouse enter and second is for mouse out. In First parameter I used animate() function that actually creates a zoom effect using css properties. In the second parameter which is mouse out I again used animate() function to get image to its original state.
All jQuery Zoom Image on Hover Code Together
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
<!DOCTYPE html> <html> <head> <style> .img-container{ border:1px solid #eeeeee; overflow:hidden; width:300px; height:220px; float:left; } img{ opacity:1; } </style> </head> <body> <div class="img-container"> <img src="images/Koala.jpg" width="300"> </div> <div class="img-container"> <img src="images/Lighthouse.jpg" width="300"> </div> <div class="img-container"> <img src="images/Penguins.jpg" width="300"> </div> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script> $(document).ready(function(){ $("img").hover(function(){ $(this).animate({width:'350px',marginLeft:'-10%',marginTop:'-10%'}); $(this).css("opacity","0.7"); }, function(){ $(this).animate({width:'300px',marginLeft:'0px',marginTop:'0px'}); $(this).css("opacity","1"); }); }); </script> </body> </html> |