Dynamically Resize an iFrame Using jQuery

I was given the task to fix a website bug of the following nature:  There is an iframe containing a “submit” button.  When the Submit button is pressed, new content is loaded into the iframe and the size of the iframe gets much larger.  Unfortunately, the containing window does not get larger and ugly scroll bars appear.  My task was to make the window get bigger and eliminate the scroll bars.  Seems easy, right?

The first thing I tried was to use jQuery’s “click” function to re-size the iframe when the submit button was clicked.  Unfortunately, JavaScript has no access to material inside the iframe if it is from a different domain.  This is for security reasons.  So, that didn’t work for me.

After searching around the Internet for a while, I stumbled upon a strong hint: the jQuery “load” method.  I could use this to trigger an event when the iframe loaded:

$('iframe').load(function() {
[re-size a div which contains the iframe here]
});

After playing with this, I noticed that the load event was triggered when the page first loaded as well as when the submit button was pressed. It had to set different window sizes in each case. Here’s how I did it:

var height_val="260px";
jQuery('iframe').load(function() {
jQuery("#iframe_container").css("height",height_val);
height_val="1430px";
});

The iframe height is initially set to 260px on page load, but the height_val variable is set to 1430px for the next trigger. When the user presses the “Submit” button, the iframe re-loads and becomes 1430 pixels tall. The iframe itself should be set to the bigger of the two sizes like this:

<div id="iframe_container">
<iframe src="http://www.yoursite.com" scrolling="auto" frameborder="0" width="100%" height="1430px">
</iframe>
</div>

The jQuery code should come after the HTML. Make sense?

If you want a solution that works for more than two different iframe sizes, check out this article, which mentions a plug-in that does it.

Let me know what you think! – Brian


2 thoughts on “Dynamically Resize an iFrame Using jQuery

  1. I am developing one page that page display mobile or tablet properly at the time display that page using iFrame not displaying correctly
    this is my code
    protected void Page_Load(object sender, EventArgs e)
    {
    String URL = http://www.aspforums.net/;

    if (!String.IsNullOrEmpty(URL))
    {

    I1.Attributes[“src”] = URL;
    }
    }

    your browser does not support IFRAMEs

Leave a Comment or Ask a Question