Get image dimensions using JavaScript

OpenJavaScript 0
Reading Time: < 1 minute 🕑

Last updated: August 2, 2022.

The dimensions of an image can be accessed via the width and height properties on an image element.

But if you try to access these right away in JavaScript, 0 is returned.

<img src="https://unsplash.it/500/500"/>

<script>

const img = document.querySelector('img');

console.log(img.width, img.height); // 0 0

</script>

This is because the image has not been loaded, and the dimensions are still unknown.

If you create a button element that returns the dimensions of the image and click it after it has loaded, the dimensions are correctly returned.

<img src="https://unsplash.it/500/500"/>

<button>Get dimensions</button>

<script>

const img = document.querySelector('img');
const btn = document.querySelector('button');

btn.addEventListener('click', function() {
  console.log(img.width, img.height);  // 500 500
});

</script>

To get the dimensions as soon as the image has loaded, you can listen out for a load event on the image element.

<img src="https://unsplash.it/500/500"/>

<script>

const img = document.querySelector('img');

img.addEventListener('load', function() {
  console.log(img.width, img.height); // 500 500
});

</script>

To get the dimensions of an image from a URL alone, you can create a new Image object in JavaScript. Then, set its src to the URL and wait for it to load within JavaScript.

const img = new Image();

img.src = "https://unsplash.it/500/500";

img.addEventListener('load', function() {
  console.log(img.width, img.height); // 500 500
});

This way, you can get the dimensions of an image without it existing as an element in the DOM.

Related links