CSS variables with JavaScript

Tram Ho

Introduce

There is a problem like this, you want your website to have orange text, background … but on Christmas and New Year you want them to be red just by creating a few custom buttons in the admin. We can’t css or add another css class, take time and inconvenience anymore. Now css variables will respond extremely quickly and simply.

Theory

The simple understanding is that instead of setting the css properties fixed for the element, we will use variables, the instructions are very easy to understand here:

https://www.w3schools.com/css/css3_variables.asp

The basic is to store variables at root and use variables to css

Apply

Back to the introductory problem, now everyone has thought about how to change the variable at root as text or background … using css variables can change simultaneously when changing root, so how to affect into root? Try a specific javascript problem to solve it: design an adjustment to change colors and font sizes using css variables.

The code is quite easy to understand, you just need to pay attention to select the color, use input type = ‘color’, while to make a bar range for font size, use input type = ‘range’. In js, input type = ‘color’ then use event change, to manipulate as soon as you drag range, you must use event mousemove, based on change and mousemove, resetting root and variables will automatically change accordingly, it’s convenient to no 😆

Share the news now

Source : Viblo