Last active — forked from webinista/has3d.js

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Testing for CSS 3D Transforms Support

View has3d.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
function has3d(){
if (!window.getComputedStyle) {
return false;
}
var el = document.createElement('p'),
has3d,
transforms = {
'webkitTransform':'-webkit-transform',
'OTransform':'-o-transform',
'msTransform':'-ms-transform',
'MozTransform':'-moz-transform',
'transform':'transform'
};
 
// Add it to the body to get the computed style
document.body.insertBefore(el, null);
 
for(var t in transforms){
if( el.style[t] !== undefined ){
el.style[t] = 'translate3d(1px,1px,1px)';
has3d = window.getComputedStyle(el).getPropertyValue(transforms[t]);
}
}
 
document.body.removeChild(el);
 
return (has3d !== undefined && has3d.length > 0 && has3d !== "none");
}

The last lines can be wrapped to return (has3d !== undefined && has3d.length > 0 && has3d !== "none");

Good point, thanks. I changed it.

I had problems with elements with position: fixed becoming invisible on Android Browser after running this function. I worked around it by sandboxing el inside an iframe: https://gist.github.com/jgonera/5250507

For performance I'd go with something like:

var has3d = (function(){
    var el = document.createElement('p'),
    has3d,
    transforms = {
        'webkitTransform':'-webkit-transform',
        'OTransform':'-o-transform',
        'msTransform':'-ms-transform',
        'MozTransform':'-moz-transform',
        'transform':'transform'
    };

    // Add it to the body to get the computed style
    document.body.insertBefore(el, null);

    for(var t in transforms){
      if (transforms.hasOwnProperty(t)) {
        if( el.style[t] !== undefined ){
            el.style[t] = 'translate3d(1px,1px,1px)';
            has3d = window.getComputedStyle(el).getPropertyValue(transforms[t]);
          }
        }
    }

    document.body.removeChild(el);

    return (has3d !== undefined && has3d.length > 0 && has3d !== "none");
}());

Just so the above function only runs the once per page instead of whenever you need to detect if we have 3d...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.