I\'m making a site that includes a range input slider. I would like the slider thumb to change colour according to the value of the slider.
For example, if the value was
You're basically looking for this, right?
const input = document.querySelector('input[type="range"]');
const style = document.createElement('style');
const head = document.head || document.getElementsByTagName('head')[0];
style.type = 'text/css';
head.appendChild(style);
input.oninput = function(e) {
const cssText = `input.slider::-webkit-slider-thumb, input.slider::-moz-range-thumb {
background-color: rgb(${255 - 2.55*e.target.value}, ${2.55*e.target.value}, 0);
}`;
if (style.styleSheet) {
style.styleSheet.cssText = cssText;
} else {
style.innerHTML = "";
style.appendChild(document.createTextNode(cssText));
}
}
.slider {
width: 60%;
margin: 50px auto;
-webkit-appearance: none;
height: 8px;
border-radius: 4px;
margin-bottom: 15px;
background-color: rgb(200, 200, 200);
}
.slider::-webkit-slider-thumb,
.slider::-moz-range-thumb {
-webkit-appearance: none;
width: 18px;
height: 18px;
border-radius: 10px;
background-color: rgb(128, 128, 0);
overflow: visible;
cursor: pointer;
}
.slidecontainer {
transform: translateY(-10px);
}
It's a bit trickier as ::webkit-slider-thumb
is a pseudo element and (i might be wrong here) i don't think you can target it directly with JavaScript. So what I did was add a tag to
and dynamically change its contents based on current input value, in a function triggered on
input
event.
It's more of a proof of concept, it can be improved by using addEventListener
and it probably looks prettier in jQuery. I'll leave all that jazz to you.
Edit: As exaneta's answer points out, you have a range of options when dealing with dynamically changing colors. While I used a simple 255 > 0
for red and 0 > 255
for green in an rgb()
, you might want to use exaneta's solution: hsl(${e.target.value}, 100%, 50%)
.