Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML range input doesn't update its value

Tags:

html

css

I created a range input in my markup, and set its value to 0, like so:

<input type="range" min="0" max="100" step="10" value="0">

I want to style it based on its current value. Let's say I want to give it a margin-top of 50px if its value is "10". I write the following simple CSS rule:

[type="range"][value="10"] {
    margin-top: 50px;
}

When sliding the range input to 10, one expects the rule to fire, but it doesn't. It does however fire when setting the input's value to "10" in the markup.

Am I missing something here? Is there really no way to style a range input according to its value, as dynamically changed by the user, with CSS only?

like image 214
Liran H Avatar asked Feb 05 '23 00:02

Liran H


1 Answers

The value of the input and the value attribute are 2 separate things. The value attribute represents the initial value of the element specified in your HTML. CSS can only target that attribute, and unfortunately can't target the actual value of the element. However, you can use javascript to read the current value on change, then update the value attribute with the value of the input, then you can target that updated attribute in CSS.

document.getElementById('input').addEventListener('change',function() {
  this.setAttribute('value',this.value);
});
input[type="range"][value="10"] {
  margin-top: 10px;
}
input[type="range"][value="20"] {
  margin-top: 20px;
}
<input id="input" type="range" min="0" max="100" step="10" value="0">
like image 186
Michael Coker Avatar answered Feb 07 '23 17:02

Michael Coker