I have a stepped slider, with non-linear steps -
code:
$(function() {
var trueValues = [5, 10, 20, 50, 100, 150];
var values = [10, 20, 30, 40, 60, 100];
var slider = $("#parkSlider").slider({
orientation: 'horizontal',
range: "min",
value: 40,
slide: function(event, ui) {
var includeLeft = event.keyCode != $.ui.keyCode.RIGHT;
var includeRight = event.keyCode != $.ui.keyCode.LEFT;
var value = findNearest(includeLeft, includeRight, ui.value);
slider.slider('value', value);
$("#amount").val(getRealValue(value));
return false;
},
});
function findNearest(includeLeft, includeRight, value) {
var nearest = null;
var diff = null;
for (var i = 0; i < values.length; i++) {
if ((includeLeft && values[i] <= value) || (includeRight && values[i] >= value)) {
var newDiff = Math.abs(value - values[i]);
if (diff == null || newDiff < diff) {
nearest = values[i];
diff = newDiff;
}
}
}
return nearest;
}
function getRealValue(sliderValue) {
for (var i = 0; i < values.length; i++) {
if (values[i] >= sliderValue) {
return trueValues[i];
}
}
return 0;
}
Here's my slider graphic:
I have the minimum value set to be at the 5 in the graphic, but I am trying to set the max (value & position) to stop at the 150 in the graphic. No matter what I've tried, the slider goes to the full end of the slider, and I always want it to stop short at the 150.
Any ideas?
The problem lies with your
values
andtrueValues
arrays and how you're handling them in thegetRealValue()
function. You're overriding the slider defaults with thetrueValues
array.I'm a little unclear as to why you want both
values
andtrueValues
. My interpretation of your code is thattrueValues
is what the slider's default values settings are, andvalues
are some sort of user-defined values.What you want to do is
.concat()
values
andtrueValues
into a single array and use that new array for the slider values. You should keeprange: 'min'
and perhaps setmax: 160
andmin: -5
to make the slider render nicely.Here's a working jsFiddle.