loading...

How to make a custom Input Range slider using HTML, CSS and JavaScript

temmietope profile image Temitope Ayodele ・2 min read

HTML has an input type of range that works awesomely. With just some CSS styling, you are good to go. The natural behavior, however, might not suit what you want. Suppose you need a custom input range for an audio player, or anything at all, where you can design the range, the controller, how do you go about it? Here is how I did mine:

HTML

  • Create a div and give it a class name
<div class="range">
</div>
Enter fullscreen mode Exit fullscreen mode
  • Within the div create another div which will serve as the slider. Give it a class name too
<div class="range" id="range">
  <div class="slider" id="slider">
  </div>
</div>
Enter fullscreen mode Exit fullscreen mode

CSS

  • Give the two divs specific height. In this example, I will use same height for both.
.range{
  height: 10px;
  border: 1px solid black;
}
.slider{
  height: 10px;
  width: 80px;
  background-color: red;
}
Enter fullscreen mode Exit fullscreen mode

JavaScript

  • Target the DOM nodes and attach each of them to variables
const rangeDiv = document.querySelector("#range");
const sliderDiv = document.querySelector("#slider");
Enter fullscreen mode Exit fullscreen mode
  • I will work with the width percentage. Hence, we will have to create a variable we will name percent.
let percent = 0;
Enter fullscreen mode Exit fullscreen mode
  • To mock the slider increment, I will use setInterval, which I have assigned to a variable named 'timer'.
let timer = setInterval(()=> {
  sliderDiv.style.width = `${percent}%`
  percent += 5
}, 1000);
Enter fullscreen mode Exit fullscreen mode

Here, we assigned the width of the styleDiv to 'percent%'. Then, at every second, the percent variable is incremented by 5.

  • Now, what happens when the width gets to 100%? We have to ensure that the timer stops. We do this by clearing the setInterval
let timer = setInterval(()=> {
  if(percent === 100){
    clearInterval(timer);
  }
  sliderDiv.style.width = `${percent}%`
  percent += 5
}, 1000);
Enter fullscreen mode Exit fullscreen mode

That's it. The custom input range slider is working perfectly. You can check the full codebase below.

I used this method to make the custom input range for my music player. Check my github repository.
https://github.com/temmietope/Music-player

Discussion

pic
Editor guide