Ian Marshall logo

Ian Marshall

iFrame Height Fix

iFrames are tricky creatures, particularly with dynamic content. Just how is anyone supposed to automatically adjust the height of an iframe to its content?



    

produces the following result:

Image free from https://pexels.com/

Well, I've written a fix. The trick, though, is that it's tough to attach a "load" event listener to iframes because iframes are literally standalone documents! The best solution, I've found, the one that is most reliable, is to add an inline JavaScript onload attribute. I know, I know: not a best practice. In fact, it's discouraged. Including by me. But I haven't yet found a way around the problem of knowing when the iframe actually loads.



    

produces the following result:

Image free from https://pexels.com/

And this seems to work well. One additional not-so-great requirement, however, was attaching the iframe_height_fix() function into global scope. But, again, without strict control over the document load event for each iframe, I didn't see another option at the time I wrote this.

Like all JavaScript and iframes, iframe-height-fix.js is dependent on the browser's cross-origin policy.

iframe-height-fix.js