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?