Get the value of an input range (without JavaScript)
A few lines of code and you have a CSS-only way to read the value of an input range slider. Powered by Scroll-driven animations, attr()
, and @property
. No more JavaScript!
⚠️ Chrome-only for now ⚠️
@property --val {
syntax: "<number>";
inherits: true;
initial-value: 0;
}
input[type="range"] {
timeline-scope: --val;
animation: --val linear both;
animation-timeline: --val;
animation-range: entry 100% exit 0%;
overflow: hidden;
/* --val will automatically update when you interact with the range slider */
}
@keyframes --val {
0% {--val: attr(max type(<number>),100)}
to {--val: attr(min type(<number>),1 )}
}
input[type="range"]::-webkit-slider-thumb{
view-timeline: --val inline;
}
The value is scoped to the input element, if you want to make it available everywhere on the page check this: Update CSS variables using range slider
Here is an example of a star rating component built using the above code:
See the Pen Star rating using scroll-driven animations by Temani Afif (@t_afif) on CodePen.
Another crazy idea with a wavy range slider.
See the Pen Single-element wavy range slider by Temani Afif (@t_afif) on CodePen.