javascriptjqueryjquery-eventsjquery-tools

Jquery slider update value on event change


I have the following code which I'm using to calculate the price of a service based on the sliders value.

It works well except the PriceVal doesn't update in real-time. It only updates once the user has lifted the mouse click from the slider.

Does anyone know how I can get it to update in real-time as the slider slides?

The page can be viewed at http://www.voxlogic.net/pricing/

$(function() {
//document.getElementById("f1").reset();
$(":range").rangeinput({ progress: true, max: 100, value:1 });  
$(":range").change(function(){
    var sliderVal = this.value;
    calculatePrice(sliderVal);      
});
$(":range").keyup(function(){
    var sliderVal = this.value;
    if (sliderVal==""){
        $("#priceVal").html('');
}
else
        {
            //check if value is from 1..25 range and correct otherwise
            if (isNaN(sliderVal)){sliderVal=1;}
            if (sliderVal<1){sliderVal=1;}
            if (sliderVal>25){sliderVal=25;}
            this.value = sliderVal;
            calculatePrice(sliderVal);
        }
    });
    
    $(":range").keydown(function(){
        var sliderVal = this.value; 
        calculatePrice(sliderVal);      
});
});

function calculatePrice(sliderVal){
    if (isNaN(sliderVal)){sliderVal=1;}
    if (sliderVal<1){sliderVal=1;}
    if (sliderVal>25){sliderVal=25;}
    var priceVal;
    if (sliderVal<=9){
        priceVal = sliderVal*6;
    }
    else if ((sliderVal>9)&&(sliderVal<=19)){
        priceVal = 9 * 6 + (sliderVal-9) * 4.5;         
    }
    else if (sliderVal>19){
        priceVal = 9 * 6 + 10 * 4.5 + (sliderVal-19) * 3.6;
    }
    $("#priceVal").html('&pound;'+priceVal.toFixed(2));
}
});

Solution

  • You need to bind the onSlide event

    onSlide

    When sliding occurs. You can cancel the action by returning false or calling preventDefault() for the event object. Note that assigning this event listener is performance heavy and may affect the smoothness of the sliding experience.

    instead of the change event.

    change

    After the range value is changed. If you slide the range by clicking on the underlying slider this is the only event that is being triggered. Note that the name is the same as the jQuery's change method and you can bind the event directly with that function. For other events you must use the bind method. This leads to more fluent syntax as shown in the example above.

    You can do this in your $.rangeinput call:

    $(":range").rangeinput({
      progress: true,
      max: 100,
      value: 1,
      onSlide: function(evt, val) {
        calculatePrice(val);
      }
    });  
    

    Or afterwards using bind.

    $(":range").bind('onSlide', function(evt, val){
      calculatePrice(val);
    });