CSS Variables + JavaScript = Win!

by kirupa | 5 June 2018

When setting CSS property values via JavaScript, especially the really complex ones, you will often find yourself wrestling with strings:


This is a companion discussion topic for the original entry at https://www.kirupa.com/html5/css_variables_js_win.htm
1 Like

One thing I’ve come to sad conclusion with is that you can’t really increment a CSS variable using just CSS. I tried incrementing a value on hover, and it didn’t work. It seems like you have to use JavaScript to permanently set a CSS variable to a new value. Using animation keyframes, for example, doesn’t change the variables in the right scope. At least that is what I seemed to find. I’d love to be proven wrong :cocktail:

CSS variables are something new to me and looks useful. Regarding “What’s old is new again” email, did CSS had variables before? I wasn’t aware of it.

Btw, @kirupa, your signature at the end of the tutorials is cool!

Glad you like the signature, kadaj :stuck_out_tongue:

CSS hasn’t had variables officially until recently. You could have used preprocessors like LESS/SASS/etc. to get similar functionality, though.

I found this article to be very informative and I learned something I did not know before. The one problem I see is browser support. According to the Mozilla article that you reference, there is no support for this in Internet Explorer. I Googled browser market share and came across this reference (https://netmarketshare.com/browser-market-share.aspx?options={“filter”%3A{"%24and"%3A[{“deviceType”%3A{"%24in"%3A[“Desktop%2Flaptop”]}}]}%2C"dateLabel"%3A"Trend"%2C"attributes"%3A"share"%2C"group"%3A"browser"%2C"sort"%3A{“share”%3A-1}%2C"id"%3A"browsersDesktop"%2C"dateInterval"%3A"Monthly"%2C"dateStart"%3A"2017-09"%2C"dateEnd"%3A"2018-08"%2C"segments"%3A"-1000"%2C"plotKeys"%3A[{“browser”%3A"Internet%20Explorer"}]}) which indicates that IE has less than a 12% market share. That means that if you want to support that browser, you’re still stuck with having an optional approach which means that it will probably mean using strings.

That is unfortunately correct, Reb! If you have to support IE, then the traditional string-based approach is what you will need to use. I should update that tutorial shortly to mention this as a note.

From what I’ve been tracking, IE is more dominant in enterprises who need access to some legacy tech that only IE works on. For consumers, the usage of IE is extremely low. Different metrics report different numbers, but the caniuse value of around 2.64% (which is from StatCounter) sounds more right than the 12% number that netmarketshare is reporting. StatCounter’s desktop browser share has IE at around 8%.

(Welcome to the forums, btw! :slight_smile:)