For a website I’m currently working on, I have an iframe in place for implementing a forum into the site, so the forum always fits nicely into the layout, also whenever the layout changes. There was only one problem with this setup, the height of the iframe was statically set and whenever a visitor was viewing a larger page/topic a scrollbar would appear within the iframe, which looks pretty nasty.
The ideal situation would be for the iframe to dynamically change it’s size whenever another page was loaded. It took a bit of trial and error, but eventually I found a way to get it done. I created this JavaScript function (inspired by various similar examples out there) to get the job done for me.
function frameResize(frameObj) { var frameHeight; // Reset the height back to it's original (shrink the frame) frameObj.height = '200px'; // Set the frame height to match the content frameHeight = frameObj.contentWindow.document.body.scrollHeight; frameObj.height = frameHeight + 'px'; }
In order for this to work, don’t forget to add the onLoad attribute to your iframe which calls the function, like this:
<iframe src="some_page.html" width="100%" height="200px" id="iframe" marginheight="0" frameborder="0" onLoad="frameResize(this);"></iframe>
Wouldn’t it be better to attach the function to window.resize?
That way if the window is resized after load, the frame will be resized as well, preventing those nasty scrollbars from popping up.
Hi Tim,
In my case, the frame was embedded within a div that automatically overflows when necessary. Whenever the window is resized, this div will make the scrollbars appear on the outer window, not on the frame itself. But, if you have a project where this is the case, you could off course bind this function to the resize event, with something like: