I'm appending the dynamically created image element to document.
var img = new Image();
img.src = 'test.jpg',
img.onload = function() {
var addedImg = container.appendChild(img);
console.log(img.width); //old width.
}
The problem here is the fact if I take image dimensions right after container.appendChild(img)
it returns the source file dimensions because the appendChild has not finished yet(not repainted?) and dimensions are not re-calculated.
var addedImg = container.appendChild(img);
console.log(img.width) //returns original width of the image
So, I'm wondering if it is possible to catch the load event for appendChild?
I know it is possible using setTimeout/setInterval
, but I guess there should be more elegant solution.
var addedImg = container.appendChild(img);
setTimeout(function() {
console.log(img.width); //return correct resolution after image dimensions were recalculated
}, 1000);
The problem with setTimeout/setInterval is the fact I don't know when element is finally appended and repainted. I have to run it on a loop.
I was trying to listen to DOMNodeInsertedIntoDocument
and DOMNodeInserted
events however it does not work.
img.addEventListener("DOMNodeInserted", onImageInserted, false);
img.addEventListener("DOMNodeInsertedIntoDocument", onImageInserted, false);
function onImageInserted(event) {
console.log(img.width); //still wrong width
}
However, it seems to run right after appendChild is fired.
Here is the fiddle so you can see what I'm talking about: http://jsfiddle.net/0zyybmf2/
Note: please don't advise to check the width of the parent container. I need to take a width of the image. Any help with this would be appreciated greatly.