jQuery – Get the actual image width and height from img tag

The <img> allows us to show an image in different size on the browser by setting its width and height. We could get the displayed image width and height in jQuery as follow.

$("#img-tag-id").css("width");
$("#img-tag-id").css("height");

 

However, sometimes we would like to get the actual image width and height of the source image. The following solution is what i found in StackOverflow.

$("<img>") // Create a new <img>
  .attr("src", $("#img-tag-id").attr("src")) // Copy the src attr from the target <img>
    .load(function() {
      // Print to console
      console.log("Width:  " + this.width);
      console.log("Height: " + this.height);
  });

 

Done =)

Reference: StackOverflow – Get real image width and height with JavaScript in Safari/Chrome?

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.