Maurice
Maurice

Reputation: 1092

Get image dimensions

I think a somehwat simple problem, but i can't find any solutions. I need to get the image dimensions from an image that is not yet loaded, but have no clue how.

I have the following html

<a href="http://domain.com/folder/bigImage.jpg" id="someID">
 <img src="http://domain.com/folder/smallImage.jpg">
</a>

Now i want to get the image dimensions of the big image, but how?


$("#someID").click(function(event){
 event.preventDefault();
 image = this.href;
 newImage = new Image();
 newImage.src = image;
 alert(newImage.width);
});

or


$("#someID").click(function(event){
 event.preventDefault();
 image = this.href;
 newImage = new Image();
 newImage.src = image;
 newImage.load(function(){
  alert(newImage.width);
 });
});

both don't work

Upvotes: 0

Views: 377

Answers (2)

Matt
Matt

Reputation: 75307

Your second example is close; you need to wait for the image to load first, before you can retrieve the dimensions of it.

$('#someId').bind('click', function (event) {
  var image = new Image();
  image.onload = function () {
    var height = this.height;
    var width = this.width;

    alert(height + " | " + width);
  }
  image.src = this.href;

  event.preventDefault();
});

You can see a working fiddle here: http://www.jsfiddle.net/JsRmU/

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630349

.load() is a jQuery function so you need a wrapper, and bind it before setting the src, like this:

$("#someID").click(function(event){
  event.preventDefault();
  var newImage = new Image();
  $(newImage).load(function(){
    alert(this.width);
  });
  newImage.src = this.href;
});

Upvotes: 2

Related Questions