This post will discuss how to get the height and width of an image in JavaScript and jQuery.

1. Using jQuery

If you’re using the jQuery library, you can programmatically load the image from the web and get its dimensions. The idea is to dynamically create an image element and use the .attr() method to set its src attribute to the image URL. Once the image is available, you can get its width and height properties. The advantage of this approach is that the image is not required to be present in the DOM.

jQuery



Edit in JSFiddle

 
Another plausible way to get the width and height of an image element in DOM is with jQuery’s .width() and .height() method. Note, this will return the size of the <img> element, and not the actual height and width of the image itself. To get the actual dimensions of an image, consider using the above method.

jQuery


HTML


CSS



Edit in JSFiddle

 
Alternatively, you can use the .css("width") and .css("height") which works similarly but returns value with units intact, like 100px.

jQuery


HTML


CSS



Edit in JSFiddle

2. Using JavaScript

You can easily get dimensions of an image using width and height properties in pure JavaScript. The following example demonstrates this. To ensure that the image is completely loaded before getting its width and height, the window’s load event handler is used.

JS


HTML


CSS



Edit in JSFiddle

 
However, this displays the size of the <img> element rather than the image’s natural height and width. Consider using the naturalWidth and naturalHeight properties to get the actual dimension of an image.

JS


HTML


CSS



Edit in JSFiddle

That’s all about getting the height and width of an image in JavaScript and jQuery.