I knew had I heard it before but I must have completely missed it anyway and forgotten to test my new Javascript widget in IE. None of the stylesheet worked in IE and it didn't make any sense. Here's how I did it first:
var closer = document.createElement('a');
a.setAttribute('style', 'float:left; font-weight:bold');
a.onclick = function() { ...
That worked in Firefox of course but not in IE. The reason is that apparently IE doesn't support this. This brilliant page says that IE is "incomplete" on setAttribute()
. Microsoft sucked again! Let's now focus on the workaround I put in place.
First I created a function to would take "font-weight:bold;..." as input and convert that to "element.style.fontWeight='bold'" etc:
function rzCC(s){
// thanks http://www.ruzee.com/blog/2006/07/\
// retrieving-css-styles-via-javascript/
for(var exp=/-([a-z])/;
exp.test(s);
s=s.replace(exp,RegExp.$1.toUpperCase()));
return s;
}
function _setStyle(element, declaration) {
if (declaration.charAt(declaration.length-1)==';')
declaration = declaration.slice(0, -1);
var k, v;
var splitted = declaration.split(';');
for (var i=0, len=splitted.length; i<len; i++) {
k = rzCC(splitted[i].split(':')[0]);
v = splitted[i].split(':')[1];
eval("element.style."+k+"='"+v+"'");
}
}
I hate having to use eval()
but I couldn't think of another way of doing it. Anybody?
Anyhow, now using it is done like this:
var closer = document.createElement('a');
//a.setAttribute('style', 'float:left; font-weight:bold');
_setStyle(a, 'float:left; font-weight:bold');
a.onclick = function() { ...
and it works in IE!