Squashing Borders on Dynamic iframes

Ah, the iframe. So we meet again. How is it that you’ve managed to survive for so long? Hiding underground for what seems like ages at a time, then suddenly uncoiling to reveal yourself and striking the unsuspecting Web developer from out of nowhere?

I’m in the middle of a project right now that, for various reasons, requires one of these little beasties for displaying some remote pages. The iframe itself is dynamically generated via JavaScript using document.createElement. No trouble there. Straightforward enough.

What wasn’t so simple was getting it to display as intended. You can use CSS to cover almost all the bases with iframe except that butt-ugly border certain browsers find it necessary to add no matter what styles you apply (cough, cough—Internet Explorer—cough, cough). The only surefire way around this is to set frameborder="0" on the iframe element itself. Presentational attributes in the markup. Ugh. Oh well, can’t win them all, right?

From here I chopped everything up into the appropriate createElement and setAttribute bits in JavaScript and set up a function that creates the whole thing when called. Bring up the test page, hit refresh, and…

The borders are back.

“What the—?!”

But only in Internet Explorer.

Sigh.

After what seemed like an interminable amount of time spent fiddling (poking Explorer with a sharp stick) and researching (Googling every variant of “stupid iframe borders in JavaScript” I could think of) I finally lucked out and hit upon this blog entry at FlashApe. Turns out that for some mysterious reason IE will only get this right if you use camel case for the attribute name value in your JavaScript.

So if you don’t want borders popping up on your dynamically generated iframe in IE, the JavaScript should look something like this (note the capital “B” in frameBorder):

var foo = document.createElement("iframe");
foo.setAttribute("src", "bar.html");
foo.setAttribute("frameBorder", "0");

All this despite the fact that the very same attribute is all lower case when in it’s in the markup.

Sure. Makes perfect sense to me.