Replacing iframe attributes with javascript (HTML5)
by
, 01-11-2012 at 08:12 PM (71915 Views)
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):
If you put this on a page containing one iframe, the scroll bars and frameborder are gone in both IE and non-IE.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>
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:Many thanks to John Scheuer, who showed how to replace iframe attributes with javascript.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>
Important: in HTML5, scripts having 'defer' must be external in order to validate.
===
Arie