Changing Range Slider background via Javascript

Viewed 499

I'm trying to change the background color of a range slider via Javascript.

I'm not getting any errors, however the background color isn't changing at all. All the other values that change work, just not the background style.

<input type="range" min="1000" max="6000" value="2000" step="100" class="slider" id="myRange" name="myRange"/>
.slider{
    -webkit-appearance: none;
    width: 100%;
    height: 20px;
    background: linear-gradient(90deg, rgb(244, 237, 144) 60%, rgb(244, 237, 144) 60%);
    outline: none;
    opacity: 1;
    -webkit-transition: 0.2s;
    transition: opacity 0.2s;
    border-radius: 12px;
    box-shadow: 0px 0.1px 10px -2px #000000;
}
document.getElementById('myRange').addEventListener('input', function(){sliderChange(this.value)});

function sliderChange(val) {
    document.getElementById('myRange').style.background = 'linear-gradient(90deg, rgb(117, 252, 117) ' + val + '%, rgb(244, 237, 144) ' + val + '%);';

    if (val == 6000) {
        var value = '6,000+';
    } else {
        var value = val.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }

    document.getElementById('sqftValue').innerHTML = value;
    var base = val * 0.12;
    var discount = base * 0.2;
    var cost = base - discount;
    document.getElementById('cost').innerHTML = cost.toFixed(0);
}

What am I missing here?

1 Answers

Try removing the semi-colon from the end of the value you're setting it to.

range.style.background = 'linear-gradient(90deg, rgb(117, 252, 117) ' + val + '%, rgb(244, 237, 144) ' + val + '%)';

The value above should like this.

range.style.background = 'linear-gradient(90deg, rgb(117, 252, 117) ' + val + '%, rgb(244, 237, 144) ' + val + '%)'

const range = document.getElementById('myRange')

range.addEventListener('input', function(){
  sliderChange(this.value)
});

function sliderChange(val) {
    range.style.background = 'linear-gradient(90deg, rgb(117, 252, 117) ' + val + '%, rgb(244, 237, 144) ' + val + '%)';
}
.slider{
    -webkit-appearance: none;
    width: 100%;
    height: 20px;
    background: linear-gradient(90deg, red 60%, blue);
    outline: none;
    opacity: 1;
    -webkit-transition: 0.2s;
    transition: opacity 0.2s;
    border-radius: 12px;
    box-shadow: 0px 0.1px 10px -2px #000000;
}
<input type="range" min="1000" max="6000" value="2000" step="100" class="slider" id="myRange" name="myRange" />

Also, using two percentage values doesn't do anything by the way.

Related