Loading a web page in an iframe . The content in the iframe can be of more height than the iframe’s height. In this case scroll bars appears. But sometimes we don’t require scroll bars and on dynamically loaded content disturbed the page in iframe.
To resize iframe height according to content, we can use javascript or jQuery. We just need to apply code on the iframe load event, so that content is loaded and height can be get at that time
Using javascript:
scrollHeight is the major property to retrieve the height of the IFRAME’s content like this:
1 | contentWindow.document.body.scrollHeight |
After the IFRAME is loaded, you can then change the height by doing the following:
1 2 3 4 5 6 7 8 9 10 | <script type="text/javascript"> function resizeIframe() { var iFrameID = document.getElementById('idIframe'); if(iFrameID) { var cont = iFrameID.contentWindow.document.body || frame.contentDocument.body // here you can make the height iFrameID.height = cont.scrollHeight + "px"; } } </script> |
On the IFRAME load event, you can call this resizeIframe function
1 | <iframe width="300" height="150" id="idIframe" onload="resizeIframe()"></iframe> |
If you are doing form submission in iframe, then additionally need to call resizeIframe from the IFRAME itself after a form-submission occurred.For that, we need to call the following code in iframe’s content script:
1 | parent.resizeIframe(); |
Using jQuery
1 2 3 | $("#IframeId").load(function() { $(this).height( $(this).contents().find("body").height() ); }); |
Sometimed we need to wait for Iframe loading, in this case we need to use javascript setInterval() function like
1 2 3 4 5 6 7 8 9 10 11 12 13 | <script> $(document).ready(function(){ var cintval = setInterval(function(){ if($('#iframeid').length) { var cont = $('#iframeid').contents().find("body").height() $('#iframeid').css('height',cont + "px"); clearInterval(cintval); } },300) }) </script> |
It will keep checking till iframe loaded fully in browser.