Resize an image proportionally with Javascript
Page: prev. | 1 | next
Recently I made some changed to the sites Gallery.
Previously clicking a sized-down version of an image on a gallery page had directed to the full-sized image resource itself (i.e. pinup.png) but I wished the sized-down version of the painting or sketch to to resize to its full-size on the page when clicked.
Thankfully, resizing an image while keeping its aspect-ratio is easy to accomplish using Javascript.
First, lets get the image.
- <img id="yourImage" src="yourImage.png" width="452" height="640" />
- <!-- The images' actual dimension of 724px x 1,024px are scaled down to 452px x 640px. -->
In this example, as the HTML comment explains, the images' actual dimension are assumed to be 724px x 1,024px and are scaled down to 452px x 640px—the actual dimensions divided by a totally arbitrary factor of 1.6.
For the sake of simplicity we'll use an onclick
event to call a function to have the image resize to its actual
dimensions when clicked, and make it a toggle by having it resize back to those scaled down values if clicked again.
- <script type="text/javascript">
- function toggleImageSize(obj) {
- var image = document.getElementById(obj);
- if (image.style.width != '724px') {
- image.style.width = '724px';
- image.style.height = 'auto';
- } else {
- image.style.width = '452px';
- image.style.height = 'auto';
- }
- }
- </script>
- <img id="yourImage" onclick="toggleImageSize('yourImage');" src="yourImage.png" width="452" height="640" />
- <!-- The images' actual dimension of 724px x 1,024px are scaled down to 452px x 640px. -->
Now when the image is clicked the onclick
event calls the toggleImageSize function passing as an argument the id of the elemant (the image)
and the image is resized to its full dimensions. When clicked again it is shrunk back to those rescaled dimensions.
The resizing is completed by setting a numeric value followed by px (pixels) for the image's width and the auto
value for the its height
which ensures it is scaled proportionally, although the width could be set with an absolute value too if you required, perhaps to make resizing
non-proportional for some reason.
The onclick
need not be attached to the image to be resized; you could, for example, attach it to a zoom icon or similar—ust ensure the
id of the image is passed to the function as an argument (this is why I have purposefully not used the this
keyword in this example, but you
could if you wished as long as the event remains attached to the image iteself). For simplicity's sake an onclick
event was used, but you
could attach an event listener for more unobtrusive script.
I hope you may find a use for it. Click the image below to test it out.
Page: prev. | 1 | next