Detecting CSS3 Transition Support

I’m in the process of developing a new blog theme for myself. I was trying to use CSS3 transitions but I wanted to fall back to JavaScript if transitions weren’t supported. I really want to avoid Modernizr if I can so I needed a quick and dirty test for detecting them. Here’s what I came up with:

var Detect = (function () { 
  function cssTransitions () { 
    var div = document.createElement("div"); 
    var p, ext, pre = ["ms", "O", "Webkit", "Moz"]; 
    for (p in pre) {
      if (div.style[ pre[p] + "Transition" ] !== undefined) {
        ext = pre[p]; 
        break; 
      } 
    } 
    delete div; 
    return ext; 
  }; 
  return { 
    "cssTransitions" : cssTransitions 
  }; 
}());

It’s simple and does the trick. Simply check the return of Detect.cssTransitions().

if (!Detect.cssTransitions()) {
   // Do JavaScript fallback here
}

You can also get the extension used in the current user-agent back from this method (ms, O, Moz, or Webkit).

Be Sociable, Share!

    3 Thoughts on “Detecting CSS3 Transition Support

    1. Will Kennedy on February 18, 2012 at 7:19 pm said:

      Why the aversion to Modernizr?

      • A number of reasons. Most of these are based on assumptions about performance of Modernizr. I do say assumptions and those may be proved wrong. I have a hunch based on implementation that performance for IE in Modernizr is slowed down. I’m doing perf testing with apps using / not using the library and will blog results. That said, I will say that using a large library to test a single feature is likely overkill. If I decide to do a lot of polyfills/shims/downlevel support, I may very well go to a modified, forked version of Modernizr.

    2. Jonathan Dickinson on February 21, 2012 at 2:06 am said:

      Some feedback:

      – Why not use a trampoline? In other words the first time the method [do the expensive check to] detect the feature and then replace the method itself with the hardcoded result.
      – You aren’t checking for non-browser-specific implementations: you should add “” to your array there.

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

    Post Navigation