I want to get the height and width of an image that does not have its width and height tag specified in the HTML source.
ie
<img src="http://www.mysite.com/imge.jpg" id="my_img" />
What I want to do is get the image’s width and the height before it loads up. I am trying to achieve the following task, if you know a better solution please suggest me.
I want to do this because I would like to keep all of the images in my site to less than or equal to 600px. So if an image’s width > 600px, I reduce it to 600px. Or else I leave its width unchanged.
My tryouts: None of the codes below work for this task, as they get the image’s size once the image is loaded; initially they display zero for width.
<script type="text/javascript">
var img = document.getElementById('my_img');
var width = img.clientWidth;
var height = img.clientHeight;
alert('Width: ' + width + ' Height:' + height); // FAIL
var timg = document.getElementById('test').width;
alert(timg); // FAIL too
</script>
My HTML code:
<img src="http://www.mysite.com/imge.jpg" id="my_img" />
Hope this is clear.
Thank you.
jsFiddle
Why use JavaScript? With this CSS rule you can limit the width to
600px: