Click here to Skip to main content
15,887,135 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello
I have an iFrame that I want to set it's height depends on it's content. I have wrote the code and it works fine, but it it will be executed in some runs of my project.

for example if I run my project, the iFrame has the default height, when I refresh the page by pressing (ctrl + F5) the function will be executed and works fine, so the iFrame height will automatically get adjusted based on content.

or I should run the project with FireBug plugin and debug it to works fine.

Do I have some mistake in my function priority?

What I have tried:

my iFrame in my html:
HTML
<iframe src="..." onLoad="ResizeIFrame(this);"></iframe>

in my javascript :
JavaScript
function ResizeIFrame(obj) {
 obj.height = obj.contentWindow.document.body.scrollHeight + 'px';
}


Thanks in Advance
With best Regards
Posted
Updated 13-Jan-17 17:24pm
v2
Comments
Ayodeji Oluwatomiwo 5-Jan-17 5:29am    
try getting the control from your javascript function and set the style height to auto.
Bob@work 11-Jan-17 15:31pm    
Changing the style of the iframe

obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';

works in IE11, chrome, and Firefox where changing the object's height attribute does not. Not sure if this will be close enough of a solution, need to check target audiences: safari, mobile browsers, etc, etc.

And changing the style only works with pages from matching sources, otherwise you'll get a security error:

"Blocked a frame with origin "http://localhost" from accessing a frame with origin "http://www.red.com". Protocols, domains, and ports must match."
Ali Majed HA 12-Jan-17 0:36am    
Hey Bob, Thanks, but the problem was it gets to work after a page refresh. I Think the problem happens in "onload" attribute of iFrame.

1 solution

I have found the solution:
I have placed the code, in document.ready as in below:
JavaScript
$(document).ready(function(){
  setInterval(function(){
   parent.$("iframe").height($("body").height));
  }, 100);
)};

This will automatically adjust the iframe height based on the content inside it.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900