How to Find Image Width in JavaScript?

Estimated read time 1 min read

To find the width of an image in JavaScript, you can use the width property of the Image object.

Here’s an example:

var img = new Image();
img.src = "example.jpg";
img.onload = function() {
  console.log("Image width: " + img.width);

In this example, the code creates a new Image object and sets its src property to the URL of the image. The onload event is used to ensure that the image is fully loaded before its width is retrieved. The width of the image is then logged to the console using console.log.

Note: The width of an image may not be immediately available if it is not fully loaded, so it is important to wait for the onload event to be triggered before retrieving the width of the image.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply