JSFiddle - React, Tailwind, and code Playground
by mrcl
HTML
<span><span class="value">0</span><input type="range" min=-100 max=100 /></span>
JavaScript
function Interpolate(start, end, steps, count) {
var s = start,
e = end,
final = s + (((e - s) / steps) * count);
return Math.floor(final);
}
function Color(_r, _g, _b) {
var r, g, b;
var setColors = function(_r, _g, _b) {
r = _r;
g = _g;
b = _b;
};
setColors(_r, _g, _b);
this.getColors = function() {
var colors = {
r: r,
g: g,
b: b
};
return colors;
};
}
$(document).on({
change: function(e) {
var self = this,
span = $(self).parent("span"),
val = parseInt(self.value),
red = {232, 9, 26),
white = new Color(255, 255, 255),
green = new Color(6, 210, 20),
start = white,
end = green;
$(".value", span).text(val);
if (val > 0) {
start = white,
end = red;
}
var startColors = start.getColors(),
endColors = end.getColors();
var r = Interpolate(startColors.r, endColors.r, 50, Math.abs(val));
var g = Interpolate(startColors.g, endColors.g, 50, Math.abs(val));
var b = Interpolate(startColors.b, endColors.b, 50, Math.abs(val));
span.css({
backgroundColor: "rgb(" + r + "," + g + "," + b + ")"
});
}
}, "input[type='range']");