View RSS Feed

molendijk

Replacing iframe attributes with javascript (HTML5)

Rating: 20 votes, 4.55 average.
I was working the other day on a script for setting the height of an iframe to match the height of its content and noticed that under certain circumstances the iframe gets its scroll bars 'back' when it shouldn't. This happens mainly when the iframe is given a very small width. Overflow: hidden solves the problem in Firefox (most of the time), but not in IE. This browsers needs scrolling="no", which also works in non-IE. However, attributes like scrolling="no" and frameborder="no", among others, are not valid in HTML5.
Searching the Internet for a solution, I found this script by jscheuer1 (http://www.dynamicdrive.com/forums/s...60454&page=2):
Code:
<script defer>
(function(run){
	var f1 = document.getElementsByTagName('iframe')[0];
	if(!f1 && window.addEventListener && !run){
		document.addEventListener('DOMContentLoaded', arguments.callee, false);
		return;
	}
	if(!f1){setTimeout(arguments.callee, 300); return;}
	f2 = f1.cloneNode(false);
	f1.src = 'about:blank';
	f2.frameBorder = '0';
	f2.scrolling = 'no';
	f1.parentNode.replaceChild(f2, f1);
})();
</script>
If you put this on a page containing one iframe, the scroll bars and frameborder are gone in both IE and non-IE.
But what about pages containing more than one iframe? I tested the following and observed that it works for all the iframes on a page:
Code:
<script defer>
(function(run){
for (i=0;i<frames.length; i++) {
	var f1 = document.getElementsByTagName('iframe')[i];
	if(!f1 && window.addEventListener && !run){
		document.addEventListener('DOMContentLoaded', arguments.callee, false);
		return;
	}
	if(!f1){setTimeout(arguments.callee, 300); return;}
	f2 = f1.cloneNode(false);
	f1.src = 'about: blank';
	f2.frameBorder = '0';
	f2.allowTransparency = 'yes';
	f2.scrolling = 'yes';

	f1.parentNode.replaceChild(f2, f1);
}
})();
</script>
Many thanks to John Scheuer, who showed how to replace iframe attributes with javascript.
Important: in HTML5, scripts having 'defer' must be external in order to validate.
===
Arie

Submit "Replacing iframe attributes with javascript (HTML5)" to del.icio.us Submit "Replacing iframe attributes with javascript (HTML5)" to StumbleUpon Submit "Replacing iframe attributes with javascript (HTML5)" to Google Submit "Replacing iframe attributes with javascript (HTML5)" to Digg

Updated 01-12-2012 at 10:36 AM by molendijk (Corrections in text)

Tags: None Add / Edit Tags
Categories
Post a JavaScript

Comments