Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (20.3k points)

I need a solution for auto-adjusting the width and height of an iframe to barely fit its content. The point is that the width and height can be changed after the iframe has been loaded. I guess I need an event action to deal with the change in dimensions of the body contained in the iframe.

1 Answer

0 votes
by (40.7k points)

Try using the code given below:

<script type="application/javascript">

function resizeIFrameToFitContent( iFrame ) {

   iFrame.width  = iFrame.contentWindow.document.body.scrollWidth;

    iFrame.height = iFrame.contentWindow.document.body.scrollHeight;

}

window.addEventListener('DOMContentLoaded', function(e) {

  var iFrame = document.getElementById( 'iFrame1' );

    resizeIFrameToFitContent( iFrame );

   // or, to resize all iframes:

    var iframes = document.querySelectorAll("iframe");

    for( var i = 0; i < iframes.length; i++) {

        resizeIFrameToFitContent( iframes[i] );

    }

} );

</script>

<iframe src="usagelogs/default.aspx" id="iFrame1"></iframe>

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...