Philipp Chapkovski
Philipp Chapkovski

Reputation: 2059

change round slider color depending on value

I am trying to let the range color change from green to red when people move the slider from 100 to 0. I use JS Round slider (https://roundsliderui.com/document.html).

MRE is here: https://codepen.io/chapkovski/pen/gORmrbR But it looks like that:

$("#slider1").roundSlider({
    sliderType: "min-range",
    value: 80,
      // svgMode: true,
    valueChange: "changeColor",
});
function componentToHex(c) {
  var hex = c.toString(16);
  return hex.length == 1 ? "0" + hex : hex;
}

function rgbToHex(r, g, b) {
  return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
}


var sliderObj = $("#slider1").data("roundSlider");
function changeColor(e) {
    const val = e.value * 2.55;
      sliderObj.rangeColor = rgbToHex(255 - val, val, 0);
}

What am I doing wrong?

Upvotes: 1

Views: 557

Answers (1)

Soundar
Soundar

Reputation: 2589

In your demo there are few problems, so you may have to correct the below things:

  1. You are setting the property value in a wrong way. To update any property value dynamically, you can follow any of the below syntax:
$("#slider1").roundSlider("option", "rangeColor", rgbToHex(255 - val, val, 0));

OR

$("#slider1").roundSlider({"rangeColor": rgbToHex(255 - val, val, 0) });

OR

sliderObj.option("rangeColor", rgbToHex(255 - val, val, 0));

https://roundsliderui.com/document.html#how-to-use-options

  1. In the color code generation logic you are doing something like this e.value * 2.55, but this will return the floating value. But hex color code won't accept the float value. So make this value round.
Math.round(e.value * 2.55)
  1. You have commented the svgMode: true, it should be enabled.

And one more suggestion, you can upgrade to the v1.6.1 for better improvement.

Here is the modified DEMO which works fine:

https://codepen.io/soundar24/pen/mdwWBzX

Upvotes: 1

Related Questions