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?

Leave a comment

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