Testing For CSS Support In Javascript

Testing For CSS Support
In Javascript

Learn how to test for CSS property
support using Javascript

I was looking to test if a certain browser (I'm looking at you Internet Explorer) supported CSS opacity while writing some jQuery code the other day. While I was aware that you could set CSS properties in Javascript, I never bothered to see if you could also feature test those same properties in Javascript. I found a nice snippet I thought I would share since I hadn't seen this before.

To test if a browser supports a specific CSS property in Javascript is pretty simple. To do so, simply create a temporary element using document.createElement("div") and then use the typeof operator on it like so:

var el = document.createElement("div"); var iefilter = typeof el.style.filter == "string";

CSS Opacity

Most likely you'll need to use this to test for the many flavors of opacity like I did. Below is an excerpt from my code:

var el = document.createElement("div"); if(typeof el.style.opacity == "string") { //Your browser supports the CSS Opacity property"; } else if (typeof el.style.filter == "string"){ //Your browser doesn't support the CSS Opacity property but does support IE filters"; } else { //"Your browser doesn't support the CSS Opacity property"; }

Browser Prefixes

We can also test for specific browser implementations of CSS properties in Javascript like so:

var el = document.createElement("div"); if(typeof el.style.borderRadius == "string") { //Your browser support the standard CSS3 border radius property } else if (typeof el.style.MozBorderRadius == "string"){ //Your browser support the Mozilla CSS3 border radius property } else if (typeof el.style.WebkitBorderRadius == "string"){ //Your browser support the Webkit CSS3 border radius property } else if (typeof el.style.KhtmlBorderRadius == "string"){ //Your browser support the KHTML CSS3 border radius property } else { //Your browser does not support the CSS3 border radius property }

CSS Hacks

If you got clever with these, my example above could probably be used for CSS hacks testing for the presence of various rendering engines. Using alittle DOM manipulation you could assign classes to the BODY element based on what browser prefixes are supported.

Further Reading: