Detecting CSS transitions support

Progressive enhancement is one of the cornerstones of good web design: You build a solid foundation that supports a broad range of different browsers, and then add features either as you detect support for them or in a way that doesn’t interfere with less capable browsers.

One of the awesome new features that’s in recent versions of Safari, Safari Mobile (iPhone browser), Chrome, the Android browser, and in Palm’s webOS is CSS transitions. Transitions work by smoothly interpolating between two states of a CSS property over time. For example, using the simple style rules below, you could have a link gradually change from yellow to red when the user moves the mouse over it:

a {color: yellow; -webkit-transition: color 1s linear;}
a:hover {color: red;}

In a more complicated example, you could use CSS transitions to slide an element off-screen when a replacement element is introduced, like the way that the “pages” slide off-screen when you click through an iPhone’s contacts.

This introduces a problem: What if you’re using JavaScript to add the new element, and you want to remove the old element after it’s off screen, and you need to support multiple browsers?

You need to be able to detect that the browser supports CSS transitions so that you know not to remove the element until it’s done animating, and so that you know that it’s OK to remove the element right away for browsers that don’t support CSS transitions. Here’s how you can detect support using JavaScript:

var cssTransitionsSupported = false;
(function() {
var div = document.createElement('div');
div.setAttribute('style', 'transition:top 1s ease;-webkit-transition:top 1s ease;-moz-transition:top 1s ease;');
cssTransitionsSupported = !!(div.style.transition || div.style.webkitTransition || div.style.MozTransition);
delete div;
})();

The variable cssTransitionsSupported will be set to true when transitions are supported, or to false when transitions are not supported.

You can then either use the transitionend (or webkitTransitionEnd for WebKit) event to detect when the transition is finished, or else immediately perform the action when transitions aren’t supported.

Note: CSS transition support has not yet made it into a release version of Firefox. The Mozilla-related code in this post is built around the Gecko 1.9.3 spec.

2 Comments on “Detecting CSS transitions support”

  1. Alex says:

    Hello,
    One can also test for CSS transitions support in Opera (10.50+) with:

    -o-transition:

    and

    div.style.OTransition

  2. admin says:

    Awesome! Thanks for the tip!

Leave a Reply