Home > other >  How to use JS to get HTML img height and set it as a variable?
How to use JS to get HTML img height and set it as a variable?

Time:02-03

In the following snippet, I'm trying to get the height of any image nested inside a particular class. Once that image height is gathered, I need to store it in a variable to be used elsewhere.

The two issues I'm running into are:

  1. The second image is coming back as 0px
  2. Storing the dynamic image height result as a variable

let getImgHeight = (()=> {
  let images = document.querySelectorAll('.wistia img');
  images.forEach(image => console.log(`${image.clientHeight}px`));
})();
<div >
  <img src="https://media.moddb.com/images/members/5/4550/4549205/duck.jpg" alt="">
  <img src="https://www.thedesignwork.com/wp-content/uploads/2011/10/Random-Pictures-of-Conceptual-and-Creative-Ideas-02.jpg" alt="">
</div>

CodePudding user response:

You get zero because you check the image height before it was loaded. You can easily check it if you wrap your function in some long timeout.

The better approach is to wait for all the loading images (ignoring ones that are already loaded) and after that get their height. Here is an example below:

let getImgHeight = (()=> {
  let images = document.querySelectorAll('.wistia img');
  Promise.all(Array.from(images)
         .filter(img => !img.complete)
         .map(img => new Promise(resolve => { 
                img.onload = img.onerror = resolve; })
         )
    ).then(() => {
        images.forEach(image => console.log(`${image.clientHeight}px`));
  });
})();
<div >
  <img src="https://media.moddb.com/images/members/5/4550/4549205/duck.jpg" alt="">
  <img src="https://www.thedesignwork.com/wp-content/uploads/2011/10/Random-Pictures-of-Conceptual-and-Creative-Ideas-02.jpg" alt="">
</div>

UPDATE 1 As long as you want

to set the height of the parent container

I'd suggest rewriting your code as follows:

const images = document.querySelectorAll('.wistia img');
for (const image of Array.from(images)) {
   if (image.complete) {
  image.parentElement.style.height = image.clientHeight   'px';
   } else {
  image.onload = () => {
     image.parentElement.style.height = image.clientHeight   'px';
  }
   }
}
<div >
  <img src="https://media.moddb.com/images/members/5/4550/4549205/duck.jpg" alt="">
</div>

CodePudding user response:

The issue is most likely that you're trying to get the height of an image that hasn't finished loading. The best way to deal with that is to use the load event listener. You can then store the height as a data-attribute which is one way of making it a dynamic variable.

document.addEventListener('DOMContentLoaded', () => {
  let images = document.querySelectorAll('.wistia img');
  images.forEach(image => {
    image.addEventListener('load', e => {
      e.target.setAttribute('data-height', `${image.clientHeight}px`)
      console.log(`${e.target.clientHeight}px`);
      if (document.querySelectorAll('.wistia img[data-height]').length === images.length) {
         console.log("ALL IMAGES LOADED");
      }
    });
  });
});
<div >
  <img src="https://media.moddb.com/images/members/5/4550/4549205/duck.jpg" alt="">
  <img src="https://www.thedesignwork.com/wp-content/uploads/2011/10/Random-Pictures-of-Conceptual-and-Creative-Ideas-02.jpg" alt="">
</div>

CodePudding user response:

I tried your code in JSFiddle and it worked as expected. Check the version of jQuery you're using.

Here is a screenshot of JSFiddle

  •  Tags:  
  • Related