Recently, I came across a range slider and I am trying to make it more dynamic. The current JavaScript code has hardcoded references to specific HTML elements, and I want to have multiple sliders on my HTML page, each functioning independently. The code snippet I am using can be found here: https://codepen.io/mukealicious/pen/jWoeZY (also provided below)
const $element = $('input[type="range"]');
const $tooltip = $('#range-tooltip');
const sliderStates = [
{name: "low", tooltip: "Good.", range: _.range(80, 100) },
{name: "med", tooltip: "Okay.", range: _.range(101, 149)},
{name: "high", tooltip: "Bad.", range: [150] },
];
var currentState;
var $handle;
$element
.rangeslider({
polyfill: false,
onInit: function() {
$handle = $('.rangeslider__handle', this.$range);
updateHandle($handle[0], this.value);
updateState($handle[0], this.value);
}
})
.on('input', function() {
updateHandle($handle[0], this.value);
checkState($handle[0], this.value);
});
// Functions to update handle value and state based on slider input
function updateHandle(el, val) {
el.textContent = Math.round(0.25*val) + "€";
}
function checkState(el, val) {
if (!_.contains(currentState.range, parseInt(val))) {
updateState(el, val);
}
}
function updateState(el, val) {
for (var j = 0; j < sliderStates.length; j++){
if (_.contains(sliderStates[j].range, parseInt(val))) {
currentState = sliderStates[j];
}
}
if (currentState.name == "high") {
updateHandle($handle[0], "150");
}
$handle
.removeClass (function (index, css) {
return (css.match (/(^|\s)js-\S+/g) || []).join(' ');
})
.addClass("js-" + currentState.name);
$tooltip.html(currentState.tooltip);
}
/* CSS styling for the range slider */
/*...CSS code provided in the original text...*/
<!DOCTYPE html>
<html lang="en" >
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>
</head>
<body>
<div class="main">
<input
type="range"
name="participants"
min="80"
max="150"
value="99"
oninput="showVal(this.value)"
onchange="showVal(this.value)"
>
<span class="rangeslider__tooltip" id ="range-tooltip"></span>
<!-- Insert Additional Range Slider HTML Code Here -->
<script>
function showVal(newVal){
console.log("updated");
</script>
<!-- include necessary external scripts-->
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src='https://andreruffert.github.io/rangeslider.js/assets/rangeslider.js/dist/rangeslider.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js'></script>
</body>
</html>
I've made several modifications to the JavaScript code, but I'm still encountering issues with changing the colors of the range sliders individually. If you have any helpful suggestions or hints, I would greatly appreciate it. Thank you.