Richard H
Richard H

Reputation: 39135

Dynamically creating an image and retrieving dimensions with jQuery

So I am dynamically creating an image and I wish to get the image dimensions. Is it possible to do this before the image is attached to the DOM? At the moment I am doing this:

 var arrow = $('<img src="' + parameters.arrowRight + '" />');
 arrow.load(function() {  
      console.log("size: " + $(this).height() + " " + $(this).width());
  });

but the height and width are both reported as zero. The image is actually being fetched as I can see the GET request in firebug.

Upvotes: 2

Views: 607

Answers (2)

vonsko
vonsko

Reputation: 395

maybe this will help:

http://api.jquery.com/load-event/

This method is a shortcut for .bind('load', handler).

The load event is sent to an element when it and all sub-elements have been completely loaded. This event can be sent to any element associated with a URL: images, scripts, frames, iframes, and the window object.

For example, consider a page with a simple image:

<img src="book.png" alt="Book" id="book" />

The event handler can be bound to the image:

$('#book').load(function() {  
   // Handler for .load() called.  
});  

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337701

No. It is not possible to get the dimensions of any element until it is attached to the DOM.

A workaround would be to give the image the css: margin-left: -10000px. You can then append it, but it will not be visible. You can then get its' dimensions and do with it as required.

Upvotes: 1

Related Questions