0

I am trying to get the height of an iframe and store it to a variable for use later. I need to wait until the iframe has loaded before I get the height, so I put it inside a timeout function. However, I noticed that the variable seems to be scoped inside the timeout function and not making it out.

        const comments = document.getElementByID('comments');
    let containerHeight = 200;
    
    const getHeight = () => {
            const container = comments.firstChild; // this is the iframe
            if(container !== null && container.offsetHeight !== 0){
      console.log(container.offsetHeight) //returns 387;
                containerHeight = container.offsetHeight;
            } else {
                setTimeout(getHeight, 500);
            }
        }

        getHeight();

        console.log(containerHeight); //returns 200. Expected 387.

I also tried setting containerHeight = getHeight() which comes back as undefined. This feels like I'm missing something obvious, but is there a different function that would be better for this use case (waiting until an element loads then storing the height as a variable)? Or is there something I'm overlooking here that's causing it to work incorrectly?

abacusrex
  • 5
  • 3
  • 1
    "*I need to wait*" - yes you need to. But your `console.log` statement doesn't, it's executed immediately. Put it inside the `if` statement instead - and remove the `return` keyword, since you [cannot return from asynchronous functions](https://stackoverflow.com/q/14220321/1048572) – Bergi Sep 20 '22 at 20:56
  • "*store it to a variable for use later*" - you're not assigning anything to your `containerHeight` variable anywhere, it keeps the initial value of `200` forever. But really you shouldn't have a global variable here - you never know when it will change and get the proper value, so it's useless. – Bergi Sep 20 '22 at 21:00
  • Sorry, that was a desperate iteration I had tried before coming here. I originally set containerHeight = container.offsetHeight inside of the timeout function. And that's where it's still returning the wrong value outside of the function. – abacusrex Sep 20 '22 at 21:00
  • Yes - the problem is not that you're logging it outside of the function, but rather that [you're logging it before it will have been updated some 500 ms later](https://stackoverflow.com/q/23667086/1048572). – Bergi Sep 20 '22 at 21:02
  • 1
    Bergi is right. The console.log will run before any value is set to the variable, unless it sets the value on the first run of getHeight. – VOL Sep 20 '22 at 21:02

0 Answers0