Dynamically change IFrame Heights


With script you can able to change/set the iframe attribute values dynamically. Sometimes we don’t know the actual height of the web page because page gets loaded dynamically and the height may varies. So here i have to calculate the page content height dynamically and set the same value in iframe height property. Mainly this is required when a page loads dynamically inside the iframe and its height can adjust automatically based on the content.(which means to show iframe without vertical scroll bar).

Sample Code


<html>
<body>
<div id=”showid”>
<table>
<tr><td>
Enter your name <input type=”text” name=”yourname”/>
Enter your age <input type=”text” name=”yourage”/>
<input type=”submit” name=”Submit”/>
</td></tr>
</table>
</div>

<script>
function setIframeHeight()
{
document.getElementById(‘testIframe’).height = document.getElementById(‘showid’).offsetHeight;
}
</script>

<iframe src=”” name=”testIframe” id=”testIframe” onload=”setIframeHeight();” />
</body>
</html>

offsetHeight

  • is a property used to retrieves the height of the element/object in pixels.
  • this value includes the height of elements borders + padding.

How it works.?

Browser rendering a page by reading each HTML tags, scripts are loaded first. When the control comes to iframe tag, we have specified an event called onload and the value setIframeHeight() method gets invoked. In this method we get the height of the page which is rendered inside the div element and set the same in iframe height.

Like this you can set the value of any iframe attributes.

document.getElementById(‘testIframe’).width = 100;
document.getElementById(‘testIframe’).scrolling = “yes”
document.getElementById(‘testIframe’).class= “css_classname”;

Advertisements

Tags: , , , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: