[javascript] Make iframe automatically adjust height according to the contents without using scrollbar?

For example:

<iframe name="Stack" src="http://stackoverflow.com/" width="740"
        frameborder="0" scrolling="no" id="iframe"> ...
</iframe>

I want it to be able to adjust its height according to the contents inside it, without using scroll.

This question is related to javascript html iframe height scrollbar

The answer is


Add this to your <head> section:

<script>
  function resizeIframe(obj) {
    obj.style.height = obj.contentWindow.document.documentElement.scrollHeight + 'px';
  }
</script>

And change your iframe to this:

<iframe src="..." frameborder="0" scrolling="no" onload="resizeIframe(this)" />

As found on sitepoint discussion.


function autoResize(id){
    var newheight;
    var newwidth;

    if(document.getElementById){
        newheight=document.getElementById(id).contentWindow.document.body.scrollHeight;
        newwidth=document.getElementById(id).contentWindow.document.body.scrollWidth;
    }

    document.getElementById(id).height=(newheight) + "px";
    document.getElementById(id).width=(newwidth) + "px"; 
}

add this to your iframe: onload="autoResize('youriframeid')"


You can use this library, which both initially sizes your iframe correctly and also keeps it at the right size by detecting whenever the size of the iframe's content changes (either via regular checking in a setInterval or via MutationObserver) and resizing it.

https://github.com/davidjbradshaw/iframe-resizer

Their is also a React version.

https://github.com/davidjbradshaw/iframe-resizer-react

This works with both cross and same domain iframes.


Here is a compact version:

<iframe src="hello.html" sandbox="allow-same-origin"
        onload="this.style.height=(this.contentWindow.document.body.scrollHeight+20)+'px';">
</iframe>

This works for me (also with multiple iframes on one page):

$('iframe').load(function(){$(this).height($(this).contents().outerHeight());});

I've had problems in the past calling iframe.onload for dynamically created iframes, so I went with this approach for setting the iframe size:

iFrame View

var height = $("body").outerHeight();
parent.SetIFrameHeight(height);

Main View

SetIFrameHeight = function(height) {
    $("#iFrameWrapper").height(height);
}

(this is only going to work if both views are in the same domain)


I wanted to make an iframe behave like a normal page (I needed to make a fullscreen banner inside an iframe element), so here is my script:

    (function (window, undefined) {

    var frame,
        lastKnownFrameHeight = 0,
        maxFrameLoadedTries = 5,
        maxResizeCheckTries = 20;

    //Resize iframe on window resize
    addEvent(window, 'resize', resizeFrame);

    var iframeCheckInterval = window.setInterval(function () {
        maxFrameLoadedTries--;
        var frames = document.getElementsByTagName('iframe');
        if (maxFrameLoadedTries == 0 || frames.length) {
            clearInterval(iframeCheckInterval);
            frame = frames[0];
            addEvent(frame, 'load', resizeFrame);
            var resizeCheckInterval = setInterval(function () {
                resizeFrame();
                maxResizeCheckTries--;
                if (maxResizeCheckTries == 0) {
                    clearInterval(resizeCheckInterval);
                }
            }, 1000);
            resizeFrame();
        }
    }, 500);

    function resizeFrame() {
        if (frame) {
            var frameHeight = frame.contentWindow.document.body.scrollHeight;
            if (frameHeight !== lastKnownFrameHeight) {
                lastKnownFrameHeight = frameHeight;

                var viewportWidth = document.documentElement.clientWidth;
                if (document.compatMode && document.compatMode === 'BackCompat') {
                    viewportWidth = document.body.clientWidth;
                }

                frame.setAttribute('width', viewportWidth);
                frame.setAttribute('height', lastKnownFrameHeight);

                frame.style.width = viewportWidth + 'px';
                frame.style.height = frameHeight + 'px';
            }
        }
    }

    //--------------------------------------------------------------
    //  Cross-browser helpers
    //--------------------------------------------------------------

    function addEvent(elem, event, fn) {
        if (elem.addEventListener) {
            elem.addEventListener(event, fn, false);
        } else {
            elem.attachEvent("on" + event, function () {
                return (fn.call(elem, window.event));
            });
        }
    }

})(window);

The functions are self-explanatory and have comments to further explain their purpose.


The hjpotter92 answer works well enough in certain cases, but I found the iframe content often got bottom-clipped in Firefox & IE, while fine in Chrome.

The following works well for me and fixes the clipping problem. The code was found at http://www.dyn-web.com/tutorials/iframes/height/. I have made a slight modification to take the onload attribute out of the HTML. Place the following code after the <iframe> HTML and before the closing </body> tag:

<script type="text/javascript">
function getDocHeight(doc) {
    doc = doc || document;
    // stackoverflow.com/questions/1145850/
    var body = doc.body, html = doc.documentElement;
    var height = Math.max( body.scrollHeight, body.offsetHeight, 
        html.clientHeight, html.scrollHeight, html.offsetHeight );
    return height;
}

function setIframeHeight(id) {
    var ifrm = document.getElementById(id);
    var doc = ifrm.contentDocument? ifrm.contentDocument: 
        ifrm.contentWindow.document;
    ifrm.style.visibility = 'hidden';
    ifrm.style.height = "10px"; // reset to minimal height ...
    // IE opt. for bing/msn needs a bit added or scrollbar appears
    ifrm.style.height = getDocHeight( doc ) + 4 + "px";
    ifrm.style.visibility = 'visible';
}

document.getElementById('ifrm').onload = function() { // Adjust the Id accordingly
    setIframeHeight(this.id);
}
</script>

Your iframe HTML:

<iframe id="ifrm" src="some-iframe-content.html"></iframe>

Note if you prefer to include the Javascript in the <head> of the document then you can revert to using an inline onload attribute in the iframe HTML, as in the dyn-web web page.


Try this for IE11

<iframe name="Stack" src="http://stackoverflow.com/" style='height: 100%; width: 100%;' frameborder="0" scrolling="no" id="iframe">...</iframe>

This works for me (mostly).

Put this at the bottom of your page.

<script type="application/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>

<script type="application/javascript" src="/script/jquery.browser.js">
</script>

<script type="application/javascript" src="/script/jquery-iframe-auto-height.js">
</script>

<script type="application/javascript"> 
  jQuery('iframe').iframeAutoHeight();
  $(window).load(
      function() {
          jQuery('iframe').iframeAutoHeight();  
      }
  );

  // for when content is not html e.g. a PDF
  function setIframeHeight() {
      $('.iframe_fullHeight').each(
          function (i, item) {
              item.height = $(document).height();
          }
      );
  };

  $(document).ready( function () {
      setIframeHeight();
  });
  $(window).resize( function () {
      setIframeHeight();
  });
</script> 

The first half is from ???, and works when there is html in the iframe. The second half sets the iframe to page height (not content height), when iframes class is iframe_fullHeight. You can use this if the content is a PDF or other such like, but you have to set the class. Also can only be used when being full height is appropriate.

Note: for some reason, when it recalculates after window resize, it gets height wrong.


Avoid inline JavaScript; you can use a class:

<iframe src="..." frameborder="0" scrolling="auto" class="iframe-full-height"></iframe>

And reference it with jQuery:

$('.iframe-full-height').on('load', function(){
    this.style.height=this.contentDocument.body.scrollHeight +'px';
});

jQuery's .contents() method method allows us to search through the immediate children of the element in the DOM tree.

jQuery:

$('iframe').height( $('iframe').contents().outerHeight() );

Remember that the body of the page inner the iframe must have its height

CSS:

body {
  height: auto;
  overflow: auto
}

This option will work 100%

<iframe id='iframe2' src="url.com" frameborder="0" style="overflow: hidden; height: 100%; width: 100%; position: absolute;" height="100%" width="100%"></iframe>

The suggestion by hjpotter92 does not work in safari! I have made a small adjustment to the script so it now works in Safari as well.

Only change made is resetting height to 0 on every load in order to enable some browsers to decrease height.

Add this to <head> tag:

<script type="text/javascript">
  function resizeIframe(obj){
     obj.style.height = 0;
     obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
  }
</script>

And add the following onload attribute to your iframe, like so

<iframe onload='resizeIframe(this)'></iframe>

I did it with AngularJS. Angular doesn't have an ng-load, but a 3rd party module was made; install with bower below, or find it here: https://github.com/andrefarzat/ng-load

Get the ngLoad directive: bower install ng-load --save

Setup your iframe:

<iframe id="CreditReportFrame" src="about:blank" frameborder="0" scrolling="no" ng-load="resizeIframe($event)" seamless></iframe>

Controller resizeIframe function:

$scope.resizeIframe = function (event) {
    console.log("iframe loaded!");
    var iframe = event.target;
    iframe.style.height = iframe.contentWindow.document.body.scrollHeight + 'px';
};

<script type="text/javascript">
  function resizeIframe(obj) {
    obj.style.height = 0;
    obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
  }
</script>

this is not working for chrome. But working for firefox.


jq2('#stocks_iframe').load(function(){
var iframe_width = jq2('#stocks_iframe').contents().outerHeight() ; 
jq2('#stocks_iframe').css('height',iframe_width); });

<iframe id='stocks_iframe' style='width:100%;height:0px;' frameborder='0'>

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to iframe

Getting all files in directory with ajax YouTube Autoplay not working Inserting the iframe into react component How to disable auto-play for local video in iframe iframe refuses to display iFrame onload JavaScript event YouTube iframe embed - full screen Change New Google Recaptcha (v2) Width load iframe in bootstrap modal Responsive iframe using Bootstrap

Examples related to height

How to Determine the Screen Height and Width in Flutter How do I change UIView Size? Adjust UILabel height to text iFrame Height Auto (CSS) CSS height 100% percent not working What is the height of Navigation Bar in iOS 7? Relative div height How to fill 100% of remaining height? CSS div 100% height Change UITableView height dynamically

Examples related to scrollbar

How to get on scroll events? Transparent scrollbar with css Remove scrollbars from textarea Body set to overflow-y:hidden but page is still scrollable in Chrome How to change scroll bar position with CSS? Prevent scroll-bar from adding-up to the Width of page on Chrome How can I add a vertical scrollbar to my div automatically? Detect Scroll Up & Scroll down in ListView Tkinter scrollbar for frame How do I make the scrollbar on a div only visible when necessary?