How to Set Custom Step Values Dynamically in jQuery UI Slider

jQuery UI Slider plugin provides an easy way to convert an HTML element into a slider. The user can select a numeric value with jQuery UI slider handle. The value can be selected by dragging the slider handle or moving the mouse or arrow keys. There are various options are available to integrate single or range sliders using jQuery UI.

In jQuery UI Slider, the step option is used to specify the interval between min and max values. For example, if the min value is 0, the max value is 10, and the step is 2, the slider intervals will be 2-4-6-8.

Sometimes we are required to set custom steps to make the slider step dynamic. But, the step option of the jQuery UI Slider plugin is not provided any configurations to step custom step values. In this example code, we will show you how to set custom step values in jQuery UI Slider and make dynamic steps.

In the following jQuery UI slider example, the user will be able to slide only the predefined steps and select only the predefined values.

HTML Code:

<div id="slider"></div>

JavaScript Code:
Use the following code to set custom snap points in the slider.

// Valid amounts that can be selected in the slider
var sliderAmountMap = [500, 750, 950, 1050, 1275, 1500];
 
$(function() {
    $("#slider").slider({
        value: 3, //array index to set the default value, for example, 3 will set 1050 as the default value and it will be selected in the slider
        min: 0, //array index to set the minimum value in the slider
        max: sliderAmountMap.length-1, //the maximum value the slider will extend
        slide: function( event, ui ) {
            $("#amount_view").val("$"+sliderAmountMap[ui.value]); //map selected value with lookup array
        }
    });
    $("#amount_view").val("$"+sliderAmountMap[$("#slider").slider("value")]);
});

Leave a reply

keyboard_double_arrow_up