Techumber

Image Zoom Effect With jQuery

Github avatar
Dimpu
September 01, 2012. 2 min read

Today we will create simple image zoom effect using jQuery. Actually i wrote this code for one of my client site jakas.in. I have converted code into jquery plugin so that we can easily share and add to your sites. Read: Create Your Own JQuery Plugin tutorial to learn how to create jquery plug-in for absolute beginners. Image Zoom Effect With jQuery

Demo

Download

Lets will create. -index.html -imageZoom.js

index.html

<html>
<head>
<script src="jquery.min.js"></script>
<script src="imageZoom.js"></script>
</head>
<body>
<div class="imgholder">
<img src="img/img1.jpg" alt="img1" width="100%" height="100%">
</div>
<div class="imgholder">
<img src="img/img2.jpg" alt="img12" width="100%" height="100%">
</div>
<body>
</html>

imageZoom.js

(function($){
//imgZoom plug in starts here
$.fn.imgZoom=function(options){
var s= $.extend( {
zoom: 25undefined
speed: 300
}undefined options);

return this.each(function(){
//getting current image
var img = $(this);
//load function trigger when image load compleate
img.load(function() {
//current width and height of the image
var w=img.width();
var h=img.height();
//on image hover event
img.hover(function(){
//incrasing image height and width.
img.stop().animate({
height: h + s.zoomundefined
width:w+s.zoomundefined
overflow:"hidden"undefined
marginLeft: -(s.zoom/2)undefined
marginTop: -(s.zoom / 2)
}undefined s.speedundefined'linear');
}undefinedfunction(){
img.stop().animate({
height: hundefined
width:wundefined
marginLeft: 0undefined
marginTop: 0
}undefined s.speedundefined'linear');
});
});
});
};
})(jQuery);

The plugin code is straight forward. -After image load in the page we get the height and width of the image. -when image hovered increasing image height and width with jquery’s animate function. -When unhover changing the height and width back to normal height and width. Note: It’s very important to use jQuery.load() function on images. Because DOM load and other resource like script and image load are different in any browsers. So Note this post it may help in feature.

CSS

<style>
.imgholder{
float: left;
width: 220px;
height: 318px;
border: none;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 5px;
box-shadow: 0px 0px 2px #999999;
overflow: hidden;
padding: 0px;
margin-left: 30px;
}
</style>

Add this code to head section of index.html.

Calling the plugin

Now we need to call your plug in inside index.html to apply it on all image on that page.

<script>
$(function(){
//simple one
$('img').imgZoom();
//if you want to change setting
var mysettings={
zoom: 55undefined
speed: 500
};
$('img').imgZoom(mysettings);
});
</script>

Add this code any where on index.html page. It’s done now open index.html page in any of your favorite browsers.


...