Reputation: 711
So I have a range/slider <input type="range">
And I got some css to make it look like this:
I would like the thumb to change color as it slides, I got the JS down that I can get the color based on it's value 1-100 but I don't know how to access the range's thumb. Everywhere I look I can access the thumb via CSS but nothing on JS.
My attempts been similar to:
slider.thumb //undefined
slider.shadowRoot //null
slider.style.webkitSliderThumb // undefined
slider.style.thumb // undefined
slider.childNodes // []
slider.children // []
Upvotes: 1
Views: 1253
Reputation: 17350
The best way is to use CSS Variables
to then pass on the color to the psuedoselector. I have put a very simple example together below:
const input = document.querySelector( 'input' );
input.addEventListener( 'input', event => {
// This assigns the strength of the color to a CSS variable, which will in turn style the slider.
input.style.setProperty( '--color', `rgba(${input.value},0,0,1)`);
})
:root {
--color: rgba(0,0,0,1);
}
input[type=range] {
width: 100%;
height: 1em;
appearance: none;
-webkit-appearance: none;
background: linear-gradient( 90deg, black, red );
}
input[type=range]::-webkit-slider-thumb {
background: var(--color, white);
appearance: none;
-webkit-appearance: none;
width: 20px;
height: 20px;
border-radius: 20px;
border: 1px solid white;
}
<input type="range" value="1" min="0" max="255" step="1" />
The elegant bit here is that its nice compatible with all old browsers as well, as you can define the default of white for those people who couldnt be bothered to get modern browsers.
And no, there is no access for pseudo elements in JS as they are... not technically there.
Upvotes: 4