Jul 03

There are certain wrong ways using JavaScript/jQuery to get the width/height of dynamic loaded image. Here are some reasons why your codes won’t work:

  • You codes run before the image is downloaded from web server,
  • event you use jQuery to bind a “load” event handler on that image, your codes won’t work when the image is loaded from browser cache(jQuery bug).

Let me show you the WRONG ways:

(WRONG)get width/height after setting html content

var html = '<img src="URL" />;
$('#my_div').html(html);
var width = $('#my_div img').width(); // may return 0

(WRONG)get width/height in “load” event handler

var html = '<img src="URL" />';
var img = $(html);
html.load(function(){
    // return 0 if image is loaded from browser cache
    var width = img.width();
});
$('#my_div').html(img);

And now, comes the right way…

The Exact way

var html = '<img src="URL" />';
$('#my_div').html(html);

var ni = new Image();
ni.onload = function(){
    var width = ni.width;
}
ni.src = img.attr(URL);

Written by ideawu at 2011-07-03 22:22:53 | Views: 1015 | tags: , ,

One Response to “The Exact Way to get Width and Height of Dynamic Loaded Image”

  1. 1. infinitevizionz Says:

    The way you explain here is easy to understand.thanks for sharing this post

Pages:

Leave a Reply

JavaScript needed to post comment!

Linode VPS