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.

index.html

There are 3 CSS variables which are Spacing, Blur, and Base Color will change the picture margin, background color as well as JS text.

We used 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 px to 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 — base, — spacing, — 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 class=hl .

Here is the final demo.

References:

https://source.unsplash.com/

https://courses.wesbos.com/account/access/5f2ae1e7f8289514d0f950fd/view/194130480

Full Stack SE. I love to build beautiful web apps and learn new technologies.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store