DEV Community

Cover image for CSS variable chapter five "how to change CSS variable value with JavaScript" ๐Ÿ”ฅ๏ธ
๐Ÿšฉ Atul Prajapati ๐Ÿ‡ฎ๐Ÿ‡ณ
๐Ÿšฉ Atul Prajapati ๐Ÿ‡ฎ๐Ÿ‡ณ

Posted on • Edited on

CSS variable chapter five "how to change CSS variable value with JavaScript" ๐Ÿ”ฅ๏ธ

Hey dear coding people,

Hope you are doing well in your coding journey

life

In the last DEV post, we have learned about "theming" ๐ŸŽ€๏ธ

And in this post, we are going to learn about "how to change CSS variable value with javascript"๐Ÿ”–๏ธ

Ummmm,๐Ÿ˜š๏ธ one question is might be crawling in your brain that why we want to change this like why somebody wants to change the CSS variable value with javascript. So my answer is just it's very useful like our DEV community theming function "DARK MODE" and "BLACK MODE".๐ŸŒ›๏ธ

Learning CSS variables

NOTE: CSS variable is livied in DOM(Document Object Model). We can't make changes in SASS and LESS(http://lesscss.org/) CSS variable with javascript.

Now let's dirty our hands with CSS code๐Ÿ™Œ๏ธ

Here I'm assuming that you are a little bit familiar with JavaScript and if not don't sweat it I'm here to assist you at every step.

This is our default webpage

So now we want to make changes in our CSS variables values

To do that we have to write these 4 lines of JavaScript code in the js file๐Ÿ“‚๏ธ

๐Ÿ“Œ๏ธ First line

var root = document.querySelector(':root');

In this javascript like of code we are targetting our CSS :root global variable and storing in javascript variable named root.

๐Ÿ“Œ๏ธ Second line

var rootStyle = getComputedStyle(root);

In this line we are getting our :root variable properties like "--red, --yellow, etc" and storing those properties to a javascript value named rootStyle.

๐Ÿ“Œ๏ธ Third line

var red = rootStyle.getPropertyValue('--red');

In this line we getting "--red" property value and storing it to javascript variable named red.

๐Ÿ“Œ๏ธ Fourth line

root.style.setProperty('--red', 'black');

In this line we are setting or changing the "--red" variable value to black.

Taddddddadadda๐Ÿ˜‰๏ธ

You have changed the css variable value with javascript

If you have any doughts in this process, I recommend you have to play with this codepen projectโœŒ๏ธ

And still, you have any difficulties in this project you have simply comment below this post me and our @dev community is ready to assist you ๐Ÿคž๏ธ:)

Top comments (0)