javascript - jQuery width() and height() return 0 for img element -
so creating new image element once response ajax call image metadata 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() , height() functions returning 0 although image has 30 x 30 px size , appears correctly on page. need dimensions in order absolutely position image.
you need wait until image has loaded have access width , height data.
var $img = $('<img>'); $img.on('load', function(){ console.log($(this).width()); }); $img.attr('src', file.url);
or plain js:
var img = document.createelement('img'); img.onload = function(){ console.log(this.width); } img.src = file.url;
also, don't need insert image dom before read width , height values, leave .loading-image
replacement until after calculate of correct positions.
Comments
Post a Comment