Jakob Nielsen
Jakob Nielsen

Reputation: 5198

Getting div height after dynamically loading images

On my website, I am rendering some content client-side. The content contains an unknown amount of image tags. I need to get the divs final height after all images have been rendered. Initially, my code looked something like this:

onst c = document.querySelector("#content");
c.innerHTML = "<img src='https://images.theconversation.com/files/292585/original/file-20190916-19040-t0k3yp.jpg?ixlib=rb-1.1.0&q=45&auto=format&w=926&fit=clip' />";
console.log("Height: " + c.offsetHeight);

Now I noticed that this is wrong, as the height will only change after the img tag has loaded. I have recreated the issue in this fiddle. https://jsfiddle.net/n0gxvq8L/

const main = () => {
   const c = document.querySelector("#content");
  c.innerHTML = "<img src='https://images.theconversation.com/files/292585/original/file-20190916-19040-t0k3yp.jpg?ixlib=rb-1.1.0&q=45&auto=format&w=926&fit=clip' />";
   console.log("Height: " + c.offsetHeight);
   setTimeout(()=> {
        console.log("Height: " + c.offsetHeight);
   }, 1000);   
}

main();

Which gives me the output

"Height: 18"
"Height: 614"

Now, I thought about using the image onload event for this purpose. This should be triggered after the image has been loaded and therefore I would be able the get the correct height of the div.

The problem though is that in my actual code I have an unknown number of images that are being loaded and I would need the height after all n images have finished loading.

The only solution I could think of is somehow (perhaps with a regex) count the number of images in the dynamically loaded content, for each of the images set up a callback, and then periodically check if enough callback calls have happened after which I can assume all images are loaded.

I am asking if somebody could think of a more elegant solution.

Upvotes: 0

Views: 154

Answers (1)

aleks korovin
aleks korovin

Reputation: 744

You could check that library which seems like was made for your case: https://www.npmjs.com/package/imagesloaded#vanilla-javascript imagesLoaded( elem, callback ). The elem could be your document.querySelector("#content"). The callback is your function where you can get correct heigh of the div.

Upvotes: 1

Related Questions