Dynamic Image Resize (Part 1)
Ever need to resize an image on the fly? When presenting images on the web people use various methods to display products to the viewer. Using JavaScript, you can resize an image for a preview, for design purposes, or for many other reasons.
First, it would be a good idea to become familiar with the image object JavaScript contains. Say we had an image on a page that we named “theImage” on a page. E.g…
Note that I set the name and the id to match. You usually don’t have to do this, but I’ve found it helps when testing in some older browsers.
To tell JavaScript that there is an image we’ll be changing, we use the Document Object Model and set the image as a variable. This would go in the tag in the header of the html document.
image = document.getElementById(’theImage’)
From here we can change things like the height and width, border, and even things like the alt tag if ever need be. The next step is pretty simple. We just set the image.width to equal whatever height you want.
Well that changes the height. However, thats no fun. Let’s use this in a function so we can call upon it anytime we need it… like when the viewer clicks on a link or the image.
{
targetImage = document.getElementById(’targetImageID’)
targetImage.height = newHeight
targetImage.width = newWidth
}
Now, we could add two links to the image, one calling a resize to a large size, and one calling a resize to a small size. We’ll use the ID from the image example from above.
<a xhref=”" mce_href=”" onclick=”changeSize(’theImage’ , 100, 100);return false;”>large<a>
That’s cool, but not very smooth. It’s fast and easy though. We could a JavaScript function to smooth the resize. That will be coming up in part to of this tutorial.