Monday, February 15, 2010

Extending Element

For those of you that work with the web on a regular basis, you'll know that trying to program or design anything in internet explorer is like trying to get blood out of a stone.

The other day I spend a great many hours trying to tame the beast, and tame the best I have!!!

Microsoft, in all their wisdom, decided back in the day that extending any element on the page was totally uncool and blocked it to programmers. Now modern browsers such as Firefox, Chrome, Safari, Opera, Any-other-browser-except-IE6-and-7 actually allow the "Element" to be extended (Yes I didn't mention IE8 because someone at Microsoft got the memo for IE8 and allowed it).

My point is, after hours of hair pulling (yes, my own), I've created a simple HACK which uses another one of Internet Explorer's non-W3C-compliant technologies to bypass this ridiculous restriction. So if there is a way of getting around it, why not simply allow it in the first place... - Well done Microsoft, once again you've managed to leave me baffled, tired and out of patience - a state-of-mind which will take me weeks to get over.

I would really like to thank this website for giving me an idea for the foundation of this hack.

And so here it is. But be warned, it simply makes extending Element "work", the performance however, will make you cry.
var seedElement=false;
if (Object.isUndefined(window.Element))
{
seedElement=true;
window.Element=function(){};
}
//Extend the Element prototype.
Element.prototype.hide=function()
{
this.style.display='none';
}

//... do more extending ...

if (seedElement)
{
var behaviors =[],
newCSS =document.createElement('style');
newCSS.id ='IE_ELEMENT_SEEDER';
newCSS.type ='text/css';
document.getElementsByTagName('head')[0].appendChild(newCSS);
for (var method in Element.prototype)
{
behaviors.push('this.'+method+'=function(){return Element.prototype.'+method+'.apply(this,arguments)}');
}
document.styleSheets[(document.styleSheets.length-1)].addRule('*','{behavior:expression('+behaviors.join(',')+')}');
delete newCSS,method;
}
delete seedElement;

No comments: