Search code examples
javascriptjqueryrangeslider

rangeslider.js - not pulling correct value number in jquery


I'm using rangeslider.js to hide or show images based on whether the value sits within a bucket ( at this point; above or below 1500 ) and I'm getting a weird response.

My slider is set up like this:

<input id="sliderone" 
    type="range"
    min="0"       // default 0
    max="3000"    // default 100
    step="1"      // default 1
    value="300"   // default min + (max-min)/2
>

My javascript is like this

var sliders = document.querySelectorAll('input[type=range]');
var result  = document.getElementById('js-result');
var values  = getValues(sliders);

$(sliders).rangeslider({
    polyfill: false
}).on('change', function() {
    var values = getValues(sliders);
    updateResult(result, values);
    console.log(values);
});

$(sliders).rangeslider({
    polyfill: false
}).on('change', function() {
    var values = getValues(sliders);
    updateResult(result, values);
    console.log(values);
});

updateResult(result, values);

function newchangepic1() {
    var newvalue = values[0];
    console.log(newvalue);

    if (newvalue < 1500) {
          $(".img-one").attr("src","images/travel.png");
    } else if ( newvalue > 1500) {
          $(".img-one").attr("src","images/plant-color.png");
    }
}

function newchangepic3() {
    var newvalue = values[1];
    console.log(newvalue);

    if (newvalue < 1500) {
        $(".img-two").attr("src","images/hdb.png");
    } else if ( newvalue > 1500) {
        $(".img-two").attr("src","images/plane.png");
    }
}

When I do

console.log(values);

It prints my array as expected, updating with each movement.

var newvalue = values[0];
console.log(newvalue);

But when I try to read one of the values inside of the array I get 300. the initial value I set in HTML.

Array results - 300 I can't get my head around why this is happening but I'm a bad at coding, so am probably missing something.

Any help?


Solution

  • var values  = getValues(sliders);
    
    $(sliders).rangeslider({
        polyfill: false
    }).on('change', function() {
        values = getValues(sliders); //<---------
        updateResult(result, values);
        console.log(values);
    });
    
    $(sliders).rangeslider({
        polyfill: false
    }).on('change', function() {
        values = getValues(sliders);//<---------
        updateResult(result, values);
        console.log(values);
    });
    

    You should probably not declare a local variable 'values' if you intend to use the global array to store the latest values.