Search code examples
javascriptoptimization

Number or String while setting style values with javascript


There are some CSS values that is defined with a number, such as opacity

I know while writing CSS, I would do:

#element {
  opacity: 1; /* without a quote mark, just 1 */
}

But when I am going to modify that opacity with JavaScript, what should I provide? only 0.5 or "0.5" ?

if I run:

typeof document.getElementById('element').style.opacity // returns "string"

So I used to provide string while modifying that. But someone reviewing my code, suggested me to provide number like:

document.getElementById('element').style.opacity = 0.5

What type should actually be used here while modifying it with JavaScript? String or Number?


Solution

  • All css values are strings (technically, DOMStrings), therefore it's cleaner to use strings as well when you change them. Still, you can use numbers (or whatever) directly, JS will just do .toString() for you.

    However, there are only a few unitless properties in css, for other numeric props you're required to provide a unit, and a bare number would be a mistake:

     style.opacity = "0.5" // fine
     style.opacity = 0.5   // fine
    
     style.width = "3px" // fine
     style.width = 3     // wrong!
    

    So I'd make it a habit to always use strings with css.

    Also, document.getElementById('element').style returns a huge object with all the possible css properties and their values which are strings:

    example:

    alignContent: ""
    alignItems: ""
    alignSelf: ""
    alignmentBaseline: ""
    all: ""
    animation: ""
    animationDelay: ""
    

    Try it in your browser console on a valid element, you'll see it. So I would suggest using strings.