This was inspired by a question on the comp.lang.javascript newsgroup way back in 2002. The poster wanted buttons to resize an image on the page, so this was my solution. Note that resizing an image in this way (altering the dimensions in the code) generally sucks, as browsers are not really designed to do this. It is — of course — better to use a graphics editor, but this is still a fun experiment! Try it out by clicking the buttons, then have a look at the code below.
We start with some javascript in a script block in the head of the document. First we get the dimensions of the original image. This will be used in the maths for adjusting the size by percentage. This is in a function called "init()" which is called from the body onload.
function init()
{
origX = document.images.theimg.width;
origY = document.images.theimg.height;
}
Next we add the code which will resize the image. This function takes one parameter inpc which is the percentage of the original image size we want to display. We do some maths based on the original image dimensions, and then the last two lines of code change the image dimensions.
function resizeImg(inpc)
{
pc = parseInt(inpc);
newX = (origX / 100) * pc;
newY = (origY / 100) * pc;
document.images.theimg.width = newX;
document.images.theimg.height = newY;
}
That concludes the javascript in the head of the document, which leads us to the body of the document. Remember we need to call the init() function from the body onload as follows.
<body onload="init()">
Now we add some (admittedly pretty poor) HTML in the shape of a form with a series of buttons for selecting a new image size. The onclick handler of each of the buttons calls the function resizeImg() which is in the document head, and passes the percentage value to it.
<form>
<input type="button" value="25%" onclick="resizeImg(25)">
<input type="button" value="50%" onclick="resizeImg(50)">
<input type="button" value="75%" onclick="resizeImg(75)">
<input type="button" value="100%" onclick="resizeImg(100)">
<input type="button" value="125%" onclick="resizeImg(125)">
<input type="button" value="150%" onclick="resizeImg(150)">
<input type="button" value="175%" onclick="resizeImg(175)">
<input type="button" value="200%" onclick="resizeImg(200)">
</form>
And finally, we put in the image, and give a name so it can be manipulated by the javascript code.
<img src="pend5.jpg" alt="picture" name="theimg" width="400" height="300">
And that's it! Please be aware that there are many, many, many better ways to do this, and this is a pretty dreadful use of HTML, but it is still a fun and giggly experiment. If you would like to use this code (bearing in mind the caveats) feel free to do so. All I ask is a credit, and maybe a link (to this page, or to my my homepage. Any comments, please email me.