DEV Community

Cover image for Custom double range slider
Sarmun Bustillo
Sarmun Bustillo

Posted on • Updated on

Custom double range slider

To create our custom slider we will make use of the native input type range, well, two of them. The idea in a nutshell is to hide the inputs and set / update visually our custom slider based on the values of those inputs.

HTML

Our structure will consist of 3 sections:

  • the text labels holding the values
  • the inputs
  • the custom slider (thumbs, track and the range between)

CSS

The main idea is pretty straight forward, visually hide the inputs and place our custom slider elements on top of the inputs.

JavaScript

We will initialise and hydrate our custom slider with the default input values and then listen for any input change so we can visually update the custom slider and the labels.

In order to achieve this we will write some functions

setLabelValue(label, input) this function takes a label together with an input. It sets the label inner text to the input's value, and will run every-time the value of the input changes

Image description

To visually set the value of our custom slider we will separate the logic into two functions, one for each side, since each calculates its values slightly different.

let's have a look at the start / left-side function.

setStartValueCustomSlider(inputStart, inputEnd, pseudoEl, range) it includes both inputs because we need to prevent our start value to go past inputEnd's value.

Image description

In code it would look something like:



 const maximum = Math.min(parseInt(inputStart.value), parseInt(inputEnd.value) - 1);


Enter fullscreen mode Exit fullscreen mode

Next, we proceed to calculate our percentage based on the input's values so we update our UI.



 const percent = ((maximum - inputStart.min) / (inputStart.max - inputStart.min)) * 100;


Enter fullscreen mode Exit fullscreen mode

Now that we know the current position, we can go ahead and visually update our thumb and the range aka what is in between both of thumbs.



pseudoEl.style.left = percent + '%';
range.style.left = percent + '%';


Enter fullscreen mode Exit fullscreen mode

Last, we need to run these two functions whenever the inputs value change, we do this by listening to the "input" event on each input.



inputStart.addEventListener('input', () => {
  setStartValueCustomSlider(inputStart, inputEnd, thumbLeft, rangeBetween);
  setLabelValue(labelMin, inputStart);
});

inputEnd.addEventListener('input', () => {
   setEndValueCustomSlider(inputEnd, inputStart, thumbRight, rangeBetween);
   setLabelValue(labelMax, inputEnd);
});


Enter fullscreen mode Exit fullscreen mode

(The end / right-side function is quite similar, you can inspect it in the demo below.)

demo

Thank you!

you can find me here My Twitter

Top comments (0)