36

How can I set CSS using javascript (I don't have access to the CSS file)?

#fade div {
  -webkit-transition: opacity 1s;
  -moz-transition: opacity 1s;
  -o-transition: opacity 1s;
  -ms-transition: opacity 1s;       
  transition: opacity 1s;
  opacity: 0;
  position: absolute;
  height: 500px;
  width: 960px;
}

For example:

document.getElementById('fade').HOW-TO-TYPE-webkit-transition = 'opacity 1s';
0

6 Answers 6

36

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';
5
  • actually, i just checked and both variants work, with and without a capital W :)
    – bardiir
    Jan 5, 2012 at 12:24
  • webkitTransition works. Thanks! But I have been trying with "moz-transition" without success :( acn you get it to work in FF?
    – Hakan
    Jan 5, 2012 at 12:30
  • 1
    Ok looks like capital letters are the way to go: document.getElementById('fade').style.MozTransition works while document.getElementById('fade').style.mozTransition doesn't
    – bardiir
    Jan 5, 2012 at 12:33
  • maybe is the case described here? bugzilla.mozilla.org/show_bug.cgi?id=607381 Jan 5, 2012 at 12:33
  • Thanks all! I must have been typing wrong or something. Now it works for me.
    – Hakan
    Jan 5, 2012 at 12:37
6

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)

6
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.

1
  • 1
    The key message of this answer is to use array notation: element.style['-webkit-transition'] = 'opacity 1s'; Jan 5, 2012 at 12:14
2

The purpose of this question is obsolete now, but the principle is still relevant.

In JavaScript, you have two ways of addressing object properties:

object.property
object['property']

The latter method, though it is less convenient, allows for property names which would be invalid, and also allows you to use a variable.

Element styles are properties of the element’s style property, so you also have a choice:

element.style.color
element.style['color']

For property names which are invalid using the dot notation, such as containing a hyphen, you can only use the second notation:

element.style['background-color']

For your convenience these troublesome names are replicated using camelCase:

element.style.backgroundColor

And, for completeness, this can also use the alternative notation:

element.style['backgroundColor']

There, you have a choice of three.

Generally, any property, such as -ms-transition can also be accessed using:

element.style['-ms-transition']

without worrying about how to express the dot notation.

Not that you need to worry about these vendor prefixes any more, but the principal still applies to other awkward properties.

0

First example:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style>
        #square {
            width: 100px;
            height: 100px;
            border-radius: 5px;
            background-color: red;
        }
    </style>
</head>
<body>
    <div id="square"></div>
    <script>
        var CSS3Error = function () {
            return {type: "Erro", message: "Classe não iniciada!"}
        }

        function CSS3(_property, _values) {
            var prefix = ["", "o", "ms", "moz", "khtml", "webkit"], values = _values, started = false, property = _property, prefixKey = 0, propertyValues = "";

            this.init = function () {
                if (!started) { 
                    started = true;

                    for (var i = 0, length = prefix.length; i < length; i++) {
                        prefix[i] += property;

                        if (prefix[i] in element.style) {
                            prefixKey = i;
                            break;
                        }
                    }

                    transitions();
                }
            }

            this.changeStyle = function (element) {
                if (started)
                    element.style[prefix[prefixKey]] = propertyValues;
                else
                    throw new CSS3Error();
            }

            this.setValues = function (value) {
                values = value;
                transitions();
            }

            function transitions() {
                propertyValues = "";

                if (property == "transition") {
                    for (var i = 0, length = values.length; i < length; i++) {
                        propertyValues += values[i];

                        if (i < length - 1)
                            propertyValues += ",";
                    }
                }
                else
                    propertyValues = values;
            }
        };

        function Method(_method)
        {
            var method = _method;

            this.delay = function () {
                var effect;

                setInterval(function () {
                    if (!effect) {
                        effect = method;
                        effect();
                    }
                    else
                        clearInterval(this);
                }, 2000);
            }
        }

        var property1 = new CSS3("border-radius", "20px"), property2 = new CSS3("transition", ["all 3s"]), property3 = new CSS3("sdads", "dasds"), element = document.querySelector("#square");

        new Method(function () {
            try {
                property1.init();
                property1.changeStyle(element);
                property2.init();
                property2.changeStyle(element);
            }
            catch(exception) {
                alert(exception instanceof CSS3Error ? exception.type + ": " + exception.message : exception.message)
            }
        }).delay();
    </script>
</body>
</html>

JS Minified (968 bytes):

function CSS3(e,t){function n(){if(l="","transition"==a)for(var e=0,t=i.length;t>e;e++)l+=i[e],t-1>e&&(l+=",");else l=i}var r=["","o","ms","moz","khtml","webkit"],i=t,o=!1,a=e,s=0,l="";this.init=function(){if(!o){o=!0;for(var e=0,t=r.length;t>e;e++)if(r[e]+=a,r[e]in element.style){s=e;break}n()}},this.changeStyle=function(e){if(!o)throw new CSS3Error;e.style[r[s]]=l},this.setValues=function(e){i=e,n()}}function Method(e){var t=e;this.delay=function(){var e;setInterval(function(){e?clearInterval(this):(e=t)()},2e3)}}var CSS3Error=function(){return{type:"Erro",message:"Classe não iniciada!"}},property1=new CSS3("border-radius","20px"),property2=new CSS3("transition",["all 3s"]),property3=new CSS3("sdads","dasds"),element=document.querySelector("#square");new Method(function(){try{property1.init(),property1.changeStyle(element),property2.init(),property2.changeStyle(element)}catch(e){alert(e instanceof CSS3Error?e.type+": "+e.message:e.message)}}).delay();

Second example:

var rules = "opacity: 0.5; transition: opacity 3s; -o-transition: opacity 3s; -ms-transition: opacity 3s; -moz-transition: opacity 3s; -webkit-transition: opacity 3s", selector = ".transition1", stylesheet = document.styleSheets[0];
("insertRule" in stylesheet) ? stylesheet.insertRule(selector + "{" + rules + "}", 0) : stylesheet.addRule(selector, rules, 0);
document.querySelector("#square").classList.toggle("transition1");

Live demo: https://jsfiddle.net/mv0L44zy/

0
function reg(){

var style = document.head.appendChild(document.createElement("style"));

style.innerHTML = "#main:after {border-right:400px solid #fde561; left:0 ; transition : 0.5s all ease}";

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.