How to adjust the width and height of an iframe to fit with content in it with JavaScript?

Spread the love

Sometimes, we want to adjust the width and height of an iframe to fit with content in it with JavaScript.

In this article, we’ll look at how to adjust the width and height of an iframe to fit with content in it with JavaScript.

How to adjust the width and height of an iframe to fit with content in it with JavaScript?

To adjust the width and height of an iframe to fit with content in it with JavaScript, we can set the iframe’s parent window’s dimensions when the iframe’s content is loading.

For instance, we write

window.onload = () => {
  parent.document.getElementById("fileUploadIframe").style.height =
    document.body.clientHeight + 5 + "px";
  parent.document.getElementById("fileUploadIframe").style.width =
    document.body.clientWidth + 18 + "px";
};

to select the parent window’s iframe from the iframe’s code with parent.document.getElementById("fileUploadIframe").

Then we set its height and width to the iframe’s body element’s clientHeight and clientWidth.

Conclusion

To adjust the width and height of an iframe to fit with content in it with JavaScript, we can set the iframe’s parent window’s dimensions when the iframe’s content is loading.

Leave a Reply

Your email address will not be published.