How to style HTML5 range input to have a different color before and after slider with CSS and JavaScript?

Spread the love

Sometimes, we want to style HTML5 range input to have a different color before and after slider with CSS and JavaScript.

In this article, we’ll look at how to style HTML5 range input to have a different color before and after slider with CSS and JavaScript.

How to style HTML5 range input to have a different color before and after slider with CSS and JavaScript?

To style HTML5 range input to have a different color before and after slider with CSS and JavaScript, we style the background with JavaScript.

For instance, we write

<div class="chrome">
  <input id="myinput" min="0" max="60" type="range" value="30" />
</div>

to add an input.

Then we write

#myinput {
  background: linear-gradient(
    to right,
    #82cfd0 0%,
    #82cfd0 50%,
    #fff 50%,
    #fff 100%
  );
  border: solid 1px #82cfd0;
  border-radius: 8px;
  height: 7px;
  width: 356px;
  outline: none;
  transition: background 450ms ease-in;
  -webkit-appearance: none;
}

to add some styling to the input.

We then change the background color dynamically when the input value changes by writing

document.getElementById("myinput").oninput = function () {
  const value = ((this.value - this.min) / (this.max - this.min)) * 100;
  this.style.background =
    "linear-gradient(to right, #82CFD0 0%, #82CFD0 " +
    value +
    "%, #fff " +
    value +
    "%, white 100%)";
};

We listen to the input event by setting oninput to a function that gets the value and the put it in the linear gradient value when we change this.input.value.

this is the range input.

Conclusion

To style HTML5 range input to have a different color before and after slider with CSS and JavaScript, we style the background with JavaScript.

Leave a Reply

Your email address will not be published. Required fields are marked *