Reputation: 83697
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.
Upvotes: 27
Views: 60637
Reputation: 2860
For me it only works with "appendTo"
$('<img src="myImage.jpeg">').load(function(){
$w = $(this).width();
$h = $(this).height();
$(this).remove()
}).appendTo("body")
Upvotes: 0
Reputation: 3017
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);
// ...
});
Upvotes: 1
Reputation: 4479
You can also use the alternate API $.load method:
$('<img src="' + file.url + '" alt="">').load( function(){ <your function implementation> });
Upvotes: 0
Reputation: 9
Try this:
$('.loading-image').replaceWith(loadedImageContainter);
$('.loading-image').load(function(){
var width = image.width();
var height = image.height();
console.log(width);
console.log(height);
});
Upvotes: -1
Reputation: 818
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');
Upvotes: -3
Reputation: 16961
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.
Upvotes: 59
Reputation: 44740
That is because your image isn't loaded when you check width
Try using load event this way
$('img').on('load',function(){
// check width
});
Upvotes: 8