27

So I am creating a new image element once I get response from AJAX call with image metadata like this:

var loadedImageContainter = $('<div class="loaded-image-container"></div>');
var image = $('<img src="' + file.url + '" alt="">');
loadedImageContainter.append(image);
$('.loading-image').replaceWith(loadedImageContainter);
var width = image.width();
var height = image.height();
console.log(width);
console.log(height);

But width() and height() functions are returning 0 although image has 30 x 30 px size and it appears correctly on the page. I need to get its dimensions in order to absolutely position the image.

David Hoerster
  • 28,421
  • 8
  • 67
  • 102
Richard Knop
  • 81,041
  • 149
  • 392
  • 552
  • Try $(window).load(function(){ var width = image.width(); var height = image.height(); console.log(width); console.log(height); }); – Patsy Issa Apr 18 '13 at 13:34

7 Answers7

59

You need to wait until the image has loaded to have access to the width and height data.

var $img = $('<img>');

$img.on('load', function(){
  console.log($(this).width());
});

$img.attr('src', file.url);

Or with plain JS:

var img = document.createElement('img');

img.onload = function(){
  console.log(this.width);
}

img.src = file.url;

Also, you don't need to insert the image into the DOM before you read the width and height values, so you could leave your .loading-image replacement until after you calculate all of the correct positions.

ahren
  • 16,803
  • 5
  • 50
  • 70
  • 2
    The jQuery code here is not working for me but the plain is, at least in Chrome v51.0.2704 using jQuery 1.12.4. It should work though. console.log($(this).width()); logs 0 no matter what, may be something strange in the width method's implementation. Accessing the width property works though console.log($(this)[0].width); or if you want to use jQuery: console.log($(this).prop("width")); – Stephen Brown Jul 14 '16 at 20:36
  • @StephenBrown I'm also getting 0 no matter what if I try to use $(this).width(); – sandre89 Feb 08 '17 at 12:49
  • 2
    I found that the load event was not always getting fired when reloading the page over and over with a combination of Control-R and Control-F5. I suspect this is because I'm iterating over a set of images in a jQuery DOM array so I have to first wait for the document.ready event to fire which could be after the image has loaded. To get around this I added a check for whether width/height are 0 and only wait for the onload event if they are. – Visualise Jun 25 '17 at 10:40
8

That is because your image isn't loaded when you check width

Try using load event this way

$('img').on('load',function(){
  // check width
});
Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111
1

As @ahren said earlier the reason is that image not loaded when you tring to get it's sizes.

If you want to fix this without jQuery you can use vanilla JS addEventListener method:

document.getElementsByTagName('img')[0].addEventListener('load', function() {
    // ...
    var width = image.width();
    var height = image.height();
    console.log(width);
    console.log(height);
    // ...
});
feeeper
  • 2,865
  • 4
  • 28
  • 42
0

You can also use the alternate API $.load method:

$('<img src="' + file.url + '" alt="">').load( function(){ <your function implementation> });
cellepo
  • 4,001
  • 2
  • 38
  • 57
0

For me it only works with "appendTo"

$('<img src="myImage.jpeg">').load(function(){
   $w = $(this).width(); 
   $h = $(this).height();
   $(this).remove()
}).appendTo("body")
dazzafact
  • 2,570
  • 3
  • 30
  • 49
-1

Try this:

$('.loading-image').replaceWith(loadedImageContainter);
$('.loading-image').load(function(){
    var width = image.width();
    var height = image.height();
    console.log(width);
    console.log(height);
});
-3

If you put it inside the AJAX call, that will work too, this is for json method

$.post("URL",{someVar:someVar},function(data){

   var totalImgs = $('body').find('img').length;

   var image = $('<img src="' + data.file[0].url + '" alt="" id="IMG_'+ totalImgs +'">');

   loadedImageContainter.append(image);
   $('.loading-image').replaceWith(loadedImageContainter);

   var width = $('#IMG_'+totalImgs).width();
   var height = $('#IMG_'+totalImgs).height();

},'json');
CG_DEV
  • 788
  • 7
  • 7