Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

151
Views
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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!