6

I have a slider in jQuery UI where I have some predefined values that the user can choose. However, right now, it just goes from 1-60 and not using my values. I have the following numbers: 1,3,5,15,30,60

This is my code:

$(document).ready(function(){
    var valMap = [1,3,5,15,30,60];
    $("#resolution-slider").slider({
        min: 1,
        max: 60,
        values: [2],
        slide: function(event, ui) {                        
            $("#resolution").val(ui.values[0]);                
            $(".resolution-preview").html(ui.values[0]);                
        }       
    });
});

How can I make the slider snap to my values in valMap?

Trolley
  • 2,328
  • 2
  • 23
  • 28
  • There is no built in functionality to do this, however you can override the `slide` event to snap to your values. See the accepted anser in this question: http://stackoverflow.com/questions/681303/is-there-a-plugin-or-example-of-a-jquery-slider-working-with-non-equably-divisib – Rory McCrossan May 02 '12 at 08:38

2 Answers2

11

Why not do:

$(document).ready(function(){
    var valMap = [1,3,5,15,30,60];
    $("#resolution-slider").slider({
      max: valMap.length - 1, // Set "max" attribute to array length
      min: 0,
      values: [2],
      slide: function(event, ui) {
        $("#resolution").val(valMap[ui.values[0]]); // Fetch selected value from array               
        $(".resolution-preview").html(valMap[ui.values[0]]);
      }  
    });
});
raveren
  • 17,799
  • 12
  • 70
  • 83
Jan
  • 5,688
  • 3
  • 27
  • 44
2

I think that's what you want, have a try the codes below:

<div id="slide"></div>

var valMap = [1,3,5,15,30,60];

$("#slide").slider({
  max: 60,
  min: 1,
  stop: function(event, ui) {
     console.log(ui.value);
  },
  slide: function(event, ui) {
    // 1,3,5,15,30,60
    return $.inArray(ui.value, valMap) != -1;
  }  
});
ijse
  • 2,998
  • 1
  • 19
  • 25