Hey dear coding people,
Hope you are doing well in your coding journey
In the last DEV post, we have learned about "theming" ๐๏ธ
CSS variable chapter four "Theming" ๐
๐ฉ Atul Prajapati ๐ฎ๐ณ ใป Mar 14 '21
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".๐๏ธ
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)