Update CSS Variable with JS
I have built projects after I graduated from Flatiron school. We can build them with JS with or without React, Vue framework. I prefer to do them plain JS, so I can get a better understand of JS. This project updates CSS Variable with JS that I have learned from wesbos. Here is the initial
index.html page. You can use Unsplash to add your own picture.
There are 3 CSS variables which are Spacing, Blur, and Base Color will change the picture margin, background color as well as JS text.
querySelectorAll to get all 3 inputs and
addEventListener method in
forEach loop to console.log when the user changes the value and when the mouse is moved.
We use the suffix
data-sizing="px" to add
sizing. We use
dataset which is an object that contains all data for a specific element. It added
data- with the element in this case we add
px and create an object for you. For example, the image below showed all data for
sizingwhen I moved the spacing bar.
We updated variables by a select the entire document which it
:root, and we are going to set up the property of
— blur using the
name property. We attached the suffix to the end because it doesn’t show
pxwhen we change the value of the variable and it is showed updated variable values.
When we used CSS variable and update that variable on any element. Any selector that inside of that element which references that variable will be using it.
We can change the scope style
JS by setting the style in
h2tag and it will show a different color because it closer than
Here is the final demo.