Customizing Components: Range Input

Wolox Engineering
Wolox
Published in
3 min readNov 12, 2015

Styling default HTML components has always been a pain for everyone. At Wolox, we found an alternative solution by creating reusable components. Keep on reading to learn what I did to get a slider just like the one in the image below. I’ll also leave the code I created so you can use it wherever you want.

When I created our slider I used this one as a guide. What I wanted was a little bit different from the one on that page, so I adjusted the missing pieces and removed the unnecessary ones.

Firstly, we are going to use the default HTML range input as the interaction tool but we’ll make it invisible and alter some divs using JavaScript to generate the desired UI. Just by looking at the previous image you can detect which divs I’m going to create in the following HTML snippet.

Related Post: Customizing Components: Radio Button

Now we are going to style this to prevent headaches. We’ll apply the following CSS and then we’ll focus on the slider’s behavior.

I made the CCS’ slider invisible and placed it on top of the other elements so the range input responds when the UI is clicked. I also added a label on the left and right that show the minimum and maximum values allowed. The thumb shows the arrows and the current slider value on hover. Now that we have a decently styled slider, let’s make it work. To do this, we’ll bind to the sliders’ change and input events. This way we’ll be able to modify our sliders’ UI frame by frame every time it updates.

Let’s go directly to the code and I’ll explain how it works afterwards.

See also: Time Zones, that thorn in our side

In the first few lines I define all the variables I’m going to use and I also define two important functions. The first important function allows the text to change it’s color based on whether the slider is filled sufficiently to cover the text or not, the second function is where the magic happens. First I get the percentage filled by the slider and afterwards I move the visual thumb to the position it should be placed and adjust the width of the fill to where the user specified. Afterwards, I update the slider’s current value and decided where the label should be placed. Finally, I add the function call and the listeners we talked about before.

Below I shared the codepen I made so you can use it!

Thanks for reading, I hope you found it helpful!

Posted by Gabriel Zanzotti (gabriel.zanzotti@wolox.com.ar)

www.wolox.com.ar

--

--