How to set CSS3 transition using javascript?

Solution 1:

You should look here: http://www.javascriptkit.com/javatutors/setcss3properties.shtml

As you can see setting CSS Properties with "-" just results in the next character to be capital:

document.getElementById('fade').style.WebkitTransition = 'opacity 1s';
document.getElementById('fade').style.MozTransition = 'opacity 1s';

Solution 2:

you should use the camelCase notation like so:

document.getElementById('fade').style.webkitTransition = 'opacity 1s';

like every property composed by more than one word and hyphen-separated (e.g. css background-position turns into js backgroundPosition.

Probably at this time not every browser adopted this notation in properties involving browser specific prefixes, so there are some browser like firefox still accepting Moz instead of moz (see https://bugzilla.mozilla.org/show_bug.cgi?id=607381)

Solution 3:

var vendors = [
    '-webkit-',
    '-o-',
    '-moz-',
    '-ms-',
    ''
];

function toCamelCase(str) {
    return str.toLowerCase().replace(/(\-[a-z])/g, function($1) {
        return $1.toUpperCase().replace('-', '');
    });
}

function setCss3Style(el, prop, val) {
    vendors.forEach(function(vendor) {
        var property = toCamelCase(vendor + prop);

        if(p in el.style) {
            el.style[p] = val;
        }
    });
}

usage :

setCss3Style(someElement, 'transition', 'opacity 1s');

Here's a live demo.