How to make a custom Input Range slider using HTML, CSS and JavaScript
Temitope Ayodele
Posted on June 10, 2019
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>
- 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>
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;
}
JavaScript
- Target the DOM nodes and attach each of them to variables
const rangeDiv = document.querySelector("#range");
const sliderDiv = document.querySelector("#slider");
- I will work with the width percentage. Hence, we will have to create a variable we will name percent.
let percent = 0;
- 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);
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);
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
Posted on June 10, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.