Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 "srting"

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 ?

like image 665
Towkir Avatar asked Apr 18 '19 11:04

Towkir


People also ask

Is a number a string in JavaScript?

JavaScript Number toString() The toString() returns a number as a string.

How do I convert a string to a number in JavaScript?

How to convert a string to a number in JavaScript using the parseInt() function. Another way to convert a string into a number is to use the parseInt() function. This function takes in a string and an optional radix. A radix is a number between 2 and 36 which represents the base in a numeral system.

What kind of values can a number type hold JavaScript?

The JavaScript Number type is a double-precision 64-bit binary format IEEE 754 value, like double in Java or C#. This means it can represent fractional values, but there are some limits to what it can store. A Number only keeps about 17 decimal places of precision; arithmetic is subject to rounding.

How do you declare a string in JavaScript?

In JavaScript, there are three ways to write a string — they can be written inside single quotes ( ' ' ), double quotes ( " " ), or backticks ( ` ` ).


1 Answers

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.

like image 101
georg Avatar answered Oct 30 '22 02:10

georg