Last Updated: February 25, 2016
·
1.714K
· dieseltravis

Feature detection for CSS Transitions on pseudo-elements like :before and :after

I needed to test for CSS Transition support on :before and :after since only Firefox and IE10 seem to support it.

var isTransitionSupported = (function (pseudo, transProp, transPropStart, transPropEnd) {
    var ticks = (new Date()).valueOf(),
        id = pseudo + transProp + '-' + ticks,
        prefixes = ['o', 'ms', 'moz', 'webkit'],
        prop = "transition: " + transProp + " 99s linear;",
        allprops = (function () {
            var props = "";
            for (var l = prefixes.length; l--;) {
                props += "-" + prefixes[l] + "-" + prop;
            }
            return props + prop;
        }()),
        body = document.body || document.createElement('body'),
        node = document.createElement('div'),
        css = "<style>" +
                    "#" + id + "{position:absolute;left:-999em;}" + 
                    "#" + id + ":" + pseudo + "{display:block;content:'M';" + transProp + ":" + transPropStart + ";}" + 
                    "#" + id + ".t" + ticks + ":" + pseudo + "{" + allprops + transProp + ":" + transPropEnd + ";}" + 
                    "</style>",
        bct = document.createElement('div'),
        isSupported = false;

    bct.id = id;
    node.innerHTML += css;
    node.appendChild(bct);
    body.appendChild(node);

    try {
        // get style value before any changes
        window.getComputedStyle(bct, ':' + pseudo).getPropertyValue(transProp);

        bct.className += "t" + ticks;

        // test style after changes
        isSupported = (window.getComputedStyle(bct, ':' + pseudo).getPropertyValue(transProp) !== transPropEnd);
    } catch (e) {}

    node.parentNode.removeChild(node);

    return isSupported;
}("before", "width", "0px", "1000px"));

document.documentElement.className += ' ' + (isTransitionSupported ? '' : 'no-') + "pseudo-trans";

Fork the gist here: https://gist.github.com/3908275

1 Response
Add your response

This came in useful today as I was looking for a simple way to detect support for pseudo-element transitions and give Safari users the same full transition experience by also applying this clever workaround for webkit browsers: http://xiel.de/webkit-fix-css-transitions-on-pseudo-elements/

Thanks for the post!

over 1 year ago ·

Have a fresh tip? Share with Coderwall community!

Post
Post a tip