How to Zoom an image using jQuery
You must had seen the zoom in and zoom out functionality for images on many sites. We can very easily achieve the Zoom In and Zoom Out functionality using jQuery toggle method. It is really simple. Let me first tell you the logic behind the implementation. Initially when document is ready then we will set the width of the image and after that on click of the image we will change the width of the image with some animation (Zoom In) and reset the width on alternate click (Zoom Out). Let's directly go to the point.
Place an image on the page.
<h1>Click image to Zoom In and Zoom Out</h1> <img src="Images/smile.png" alt="Smile" id="imgSmile" />
Now jQuery code.
$(document).ready(function(){ $('#imgSmile').width(200); $('#imgSmile').mouseover(function() { $(this).css("cursor","pointer"); }); $("#imgSmile").toggle(function() {$(this).animate({width: "500px"}, 'slow');}, function() {$(this).animate({width: "200px"}, 'slow'); }); });
Let's understand the code.
Initially we have set the image width to 200px and on mouseover event, mouse cursor is changed to pointer. So it gives an impression that image is clickable.
As in the above code, toggle method is used. toggle method binds two or more handlers to the element, which will be executed on click. If two handlers are specified then on first click first handler will be called and on second click second handler will be called. Toggle method internally makes a call to click event only.
So in our code, when first time is click width is increased to 500 px and on second click width is reset to 200 px. Animate function is also used to show zooming effect in animated manner. To use animate, we need to pass CSS properties to be set and the timespan. Timespan value can be in milliseconds or one of the string values from 'slow', 'normal' or 'fast'.
Feel free to contact me for any help related to jQuery. I will gladly help you.