Check out a free preview of the full Dynamic CSS with Custom Properties (aka CSS Variables) course

The "Dynamic Form Element Styling" Lesson is part of the full, Dynamic CSS with Custom Properties (aka CSS Variables) course featured in this preview video. Here's what you'd learn in this lesson:

Lea live codes a slider with dynamic styling by combining JavaScript and CSS.

Preview
Close

Transcript from the "Dynamic Form Element Styling" Lesson

[00:00:00]
>> Another effect that forces us to combine CSS and JavaScript and write CSS in JavaScript quite frequently is when we want the form elements styling to depend on its value. For example, we have a slider and we want to change its styling based on its current value. So custom properties allow us to just set a value property and do everything else in CSS.

[00:00:23]
So we can go over every input in our page, or we could go over just range inputs, but in this case we're going over all inputs. And we set a value custom property with the current value. And then we also obviously need to monitor the input event so that we can update this value property otherwise it wouldn't be very useful.

[00:00:44]
And let's see how we can use that, so here we have a slider we've applied slight a little bit of CSS to make it styleable. And we have this fixed radial gradient. And the code that I've showed you is already applied here. So what I want is for this.

[00:01:07]
Gradient to adjust, so that when I move the slider handle, it actually shows me how far I am. So the value property would range from 0 to 100 because it's just reflecting the value of the sliders. And right now in outage the mail, I just have an input type equals range with no min and max specified so I get the 0 to 100 that is the default.

[00:01:33]
I can go there and multiply value with. I have 0 to 100, I wanna make it 0 to 100%. So just be more multiplying it by 1%. And as you can see it adapts, it needs a little bit of tweaking to make to actually look nice but the main idea is there.

[00:02:02]
And similarly, if I wanted, I could modify the actual hue of the color to also adapt. Or I could style I don't know, the box shadow based on the value like the sky's the limit. The JavaScript just sets the value like just the pure number, that you've selected on the slider.

[00:02:24]
And the CSS can then go crazy without having to make any changes to the JavaScript.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now