Tuesday, 17 July 2012

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.

     {$(this).animate({width: "500px"}, 'slow');},
     {$(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'.
See live Demo and Code.  

No comments:

Post a Comment

Thank you so much for providing your valuable feedback. I will will look into them and update my skills & technologies accordingly.