Fr0z3n
Fr0z3n

Reputation: 1576

Get Width/Height of img Loaded by JS

I need to get the Width and Height of a img tag, when it's replaced by javascript.

I tried using jQuery's width() / height() but always return the values of the cached image, and not the ones of the new image.

I need that because i have a function to scale the background-size of a div depending on size of the image loaded.

I searched a lot on google and here but can't find a solution.

Upvotes: 0

Views: 100

Answers (1)

Ravinder Singh
Ravinder Singh

Reputation: 3133

To get the dimension of image try this :

var currentImage = $("img"); // get image element
var img = new Image();
img.onload = function() {
    var width = this.width;
    var height = this.height;
}
img.src = currentImage.attr('src');

Upvotes: 1

Related Questions