iFrame dynamic height 100%

Scenario:

I use an iframe to display some content within my own domain.

I use a width of 100%, but I always have to specify the height in pixels, since there is no such thing as “height=100%” . I want the iframe to change it’s height automatically and display the contents without scrollbars. The problem is the content inside the iframe starts at a given height, then varies (gets bigger or smaller) depending on what you click. So If I set the height too big, I end up with a large bottom margin,  if I set it too small, I clip the content.

Question:

Is there a way to resize the iframe height attribute dynamically as the height of the contents inside the iframe changes to achieve a “height=100%” behavior?

Answer:

Yes it can be done!

Solution #1: (Iframe reloads)

I found this code that binds to the moment the iframe loads and sets the height. Put this script before the iframe code.

jQuery(document).ready(function($) {
$("iframe").bind("load",> function() {
var embed_height = $("iframe").contents().find("body").height();
$("iframe").height(embed_height);
});
});

Solution #2: (Iframe changes height without reloading)

I based this code on the previous example. It will resize the iframe based on the height of the contents every second. Again, put this script before the iframe code.

jQuery(document).ready(function($) {
func­tion resize() {
var embed_height = $(“iframe”).contents().find(“body”).height();
$(“iframe”).height(embed_height);
set­Time­out( resize, 1000 );
}
resize();
});

Conclusion:

I tried other ways to do this, like binding the resize to a .click() event, but I was unable to do it on anything other than .hover(). Seems that getting events from an iframe is bound to be the topic of another post. So I had to settle for the timer (Solution #2). JavaScript is awesome!

Leave a Reply

Your email address will not be published. Required fields are marked *

*