Hey, I'm trying to change the size of an image with javascript. The jS file is separate from the html page.
I want to set the height and width of an image in the JS file.
Any good ways on doing this?
Thanks for any help.
Hey, I'm trying to change the size of an image with javascript. The jS file is separate from the html page.
I want to set the height and width of an image in the JS file.
Any good ways on doing this?
Thanks for any help.
Once you have a reference to your image, you can set its height and width like so:
var yourImg = document.getElementById('yourImgId');
if(yourImg && yourImg.style) {
yourImg.style.height = '100px';
yourImg.style.width = '200px';
}
In the html, it would look like this:
<img src="src/to/your/img.jpg" id="yourImgId" alt="alt tags are key!"/>
You can change the actual width/height attributes like this:
var theImg = document.getElementById('theImgId');
theImg.height = 150;
theImg.width = 150;
If you want to resize an image after it is loaded, you can attach to the onload
event of the <img>
tag. Note that it may not be supported in all browsers (Microsoft's reference claims it is part of the HTML 4.0 spec, but the HTML 4.0 spec doesn't list the onload
event for <img>
).
The code below is tested and working in: IE 6, 7 & 8, Firefox 2, 3 & 3.5, Opera 9 & 10, Safari 3 & 4 and Google Chrome:
<img src="yourImage.jpg" border="0" height="real_height" width="real_width"
onload="resizeImg(this, 200, 100);">
<script type="text/javascript">
function resizeImg(img, height, width) {
img.height = height;
img.width = width;
}
</script>
Changing an image is easy, but how do you change it back to the original size after it has been changed? You may try this to change all images in a document back to the original size:
var i,L=document.images.length; for(i=0;i<L;++i){ document.images[i].style.height = 'auto'; //setting CSS value document.images[i].style.width = 'auto'; //setting CSS value // document.images[i].height = ''; (don't need this, would be setting img.attribute) // document.images[i].width = ''; (don't need this, would be setting img.attribute) }