JavaScript Get Image Dimensions (Width & Height) Examples
Have you ever wanted to get image dimensions using JavaScript? In this article, I am going to share an easy way to use JavaScript to get image dimensions (width & height).
How to use JavaScript to Get Image Dimensions (Width & Height)
Following is the complete HTML + JavaScript source code that shows how to get the image dimensions (width & height) when the page is loaded:
Example: Get Image Width & Height (dimensions) using JavaScript
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Javascript Get Image Dimensions</title> </head> <body> <img src="images/banner.png" id="my_img" /> <script type="text/javascript"> var img = document.getElementById('my_img'); var width = img.clientWidth; var height = img.clientHeight; alert( 'Width: ' + width + ' Height:' + height ); </script> </body> </html>
The given code assumes that there is an image with ID “my_img” and the dimensions of this image needs to be found. When the above code is executed, the page will alert the width and height of the image.
Note
The image has to be completely loaded in order to get it’s size, or the width & height values are incorrectly shown as zero.
That’s it!
Do you know of any other ways to find image width and height using JavaScript? Feel free to share by commenting below.