Tuesday, October 25, 2011

JS getCSSPropertyName Function

I was re-checking @LeaVerou talk at jsconf.eu looking forward to see mine there too to understand how to improve and specially what the hell I have said for 45 minutes :D

Lea made many valid points in her presentation but as is for supports.property case, you never want to go too deep into a single point of your talk so ... here I come.

getCSSPropertyName Function

This function aim is to understand if the current browser supports a generic CSS property. If property is supported, the whole name included prefix will be returned.

var getCSSPropertyName = (function () {
var
prefixes = ["", "-webkit-", "-moz-", "-ms-", "-o-", "-khtml-"],
dummy = document.createElement("_"),
style = dummy.style,
cache = {},
length = prefixes.length,
i = 0,
pre
;
function testThat(name) {
for (i = 0; i < length; ++i) {
pre = prefixes[i] + name;
if (
pre in style || (
(style.cssText = pre + ":inherit") &&
style.getPropertyValue(pre)
)
) return pre;
}
return null;
}
return function getCSSPropertyName(name) {
return cache.hasOwnProperty(name) ?
cache[name] :
cache[name] = testThat(name)
;
};
}());

The function returns a string or null, if no property has been found.

// enable HW acceleration
var cssPropertyName = getCSSPropertyName("transform");
if (cssPropertyName != null) {
node.style.cssText += cssPropertyName + ":translate3d(0,0,0);";
}

Please feel free to test this function and let me know if something went wrong, thanks ;-)

No comments:

Post a Comment