Tuesday, September 01, 2009

Dynamically setting the height of an iframe

This is reposted from blog.pixelmedia.com.


Recently, we had a situation that required us to pull in some content from one server to another using an iframe. Generally, this is something we would try to avoid, but we needed to pull some data from a new .NET application into a legacy ColdFusion application.

Unfortunately, the height of the page being pulled in would vary wildly. This led to a fairly disappointing experience where the page was either far too long, or content in the iframe was cut off and the user had to scroll within the iframe to see everything.

We came up with what we thought might be an interesting solution. If the page loading inside of the iframe (the child page) could calculate its height, and somehow let the parent page know, the parent page should be able to reset the height of the iframe.

With a little inspiration, we came up with a pretty neat solution that we’d like to share. Our solution requires that you have the ability to edit the code of both the parent and child pages.

The child page being loaded into the iframe will simply reset the location of the parent page, and include a hash with the height of itself.



<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.js"></script>
<script>
var parentUrl = "http://kingston/other/test/iframe-outside.html";

setHash = function() {
parent.location = parentUrl + "#" + $('body').height();
}();
</script>

We’re using jQuery here to easily get the height of the <body> tag.

On the parent page that includes the iframe, we’ll again use jQuery and write a small function that gets the height from the hash in the URL, and uses that to reset the height of the iframe.

function setHeight() {
var newHeight = parseInt(location.hash.substring(1)) + 50;
$('#hashFrame').attr('height', newHeight);
}

We ran into a bit of an issue: the page we were loading was taking a few seconds to load, and we didn’t want to set our height on the iframe until the content within the iframe had finished loading (and it had a chance to set the proper height to the url hash).

More jQuery to the rescue! The jQuery .load() method allowed us to call our setHeight() function after the iframe had finished loading.

$('#hashFrame').load( function() {
setHeight();
});

Putting it all together gave us a great way to use our new application inside our legacy application, and make it faily seamless to the end user.