Yasmin Ledesma

Day 3/30: CSS Variables with JS #JavaScript30

Overview of the challenge

Wes Bos gives out a bunch of code and I'm supposed to make everything work by the end of the month?

December 3rd, and today's pick deals with CSS variables, and with how to change them using JavaScript.

This time I only started with an HTML and a CSS files as a base and didn't had to tamper with anything inside them. So after a quick look, I went straight to coding the script. For my surprise, I didn't had to look at this exercise video today to come up with a solution, and that made me really happy! (even though Wes Bos code is shorter here.) Still, I watched after it finishing, and learned some extra things, like the dataset property.

Train of thought...

CSS Variables with JS

Everytime the user moves the levers on the page, its respective CSS property increases or decreases in value.

  1. See how to reference a CSS variable in JS.

  2. Get the root element, then get its style values with computedStyle.

  3. Get the two ranges and the base by ID, maybe? Then reference their value attributes to change them. Call an event listener on each one? See if you can move the handler bars on change. (Yes, you can. And you get the current value with e.target.value.)

  4. Add an event listener that loops through the CSS variables with forEach. (Can't)

  5. Set the attribute value of each variable dynamically using e.target.value.

  6. Figure out how to change the --variable based on the new value of your levers. (You can target and change variables by referencing them from the root element (i.e. root.style.cssText = "--spacing: 20px")) (Just reference it from the document element.)

  7. Find a way to reference the --variable, so you can put a ${variable} in its place. (Use e.target.id to pass the name as a string!)

  8. Figure out the same for the color picker. (Same way, just remove the px at the end of ${e.target.value} and add a conditional to make it work with whatever constant passed.)

What I learned

And it's done!

You can find my solution to this challenge in its repository. You can also try it out live on CodePen!

#challenge #javascript