Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>DOM elements have dimensions only when added to a parent, as dimension is determined by the rendering engine. To go around this issue, have a <code>&lt;div&gt;</code> container absolutely positioned off screen, add the image to it first, get the dimension, then add the image at it's final destination.</p> <p>Something like :</p> <pre><code>var _offscreen = $('&lt;div&gt;&lt;/div&gt;') .css({position:'absolute',left:'-999999px',width:'400px',height:'600px'}) .appendTo($('body')); var img = $('&lt;img&gt;/img&gt;') .attr('src',"http://l1.yimg.com/a/i/ww/news/2011/03/25/zo.jpg") .load(function() { var $this = $(this); $this.appendTo(_offscreen); setTimeout(function() { var width = $this.width(); var height = $this.height(); alert($this.attr('src') + ' = ' + width + "x" + height); }, 0); }); </code></pre> <p>** <strong>EDIT</strong> **</p> <p>I just updated the code above. As it turned out, you need to let the rendering engine draw the image (of course!) and <em>then</em> get the dimension. So that edit works.</p> <p>This could be put inside a convenient function like :</p> <pre><code>$('imageElement').loadImage("path/to/image", function() { alert("Image " + $(this).attr('src') + " loaded: " + $(this).width() + "x" + $(this).height()); }); </code></pre> <p>** <strong>UPDATE</strong> **</p> <p>I thought you might like to see the code above put into a <a href="http://jsfiddle.net/fUyG6/1/" rel="nofollow">JQuery plugin</a>... just for fun :) It just works, there is no validation done (i.e. it won't check if you pass other elements than <code>&lt;img&gt;</code>), and if the selector returns more than one element, the plugin will load the same image into each selected elements. You could actually have the plugin argument <code>url</code> be an array (optional) and load each image of the array in each selected element, etc. Just a thought.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload