Friday, December 23, 2011

Resizing an iframe based on its content

Recently I wanted to allow a scrollable DIV to be scrolled by dragging with the mouse. When a user clicks and moves the mouse inside the DIV the content of the DIV is scrolled, in this case only vertically (up or down). I quickly found a JavaScript that more or less did that job.
The content of the scrollable DIV is a second HTML page that is loaded in an iframe. Because an iframe is itself a scrolling container I disabled scrolling on the iframe. Here is the body of the HTML page that contains the iframe:
<div id="scroller" style="width: 500px; height: 100px; overflow-y: scroll">
    <iframe style="border-style: none" width="450" height="300" scrolling="no"
        src="page2.htm" />
</div>
Now when page2.htm does not fit into the iframe's width and height, part of its HTML is invisible and will never become visible since we disabled scrolling on the frame. The frame's height="300" may or may not be large enough to show all frame content. This, of course, depends on the amount of content in the page2.htm source.

Ideally the height of the iframe should be adapted to the height of its content. After some searching and experimenting, a single line of inline JavaScript solved the problem:
<div id="scroller" style="width: 500px; height: 100px; overflow-y: scroll">
    <iframe style="border-style: none" width="450" scrolling="no"
        src="page2.htm"
        onload="this.height = this.contentWindow.document.body.scrollHeight" />
</div>
Note that the arbitrary height="300" attribute has been removed from the iframe element. The height is now determined using the height of the framed page (actually, its body), after that page has finished loading.

No comments:

Post a Comment