I have found two excellent jquery plugins for generating a slider for a web form, which degrade nicely in browsers that do not support javascript have styles turned off etc.
In Es6 you can find your closest number by following ..
function findClosest(array, value) {
return array.sort( (a, b) => Math.abs(value - a) - Math.abs(value - b) )[0];
}
let array = [1, 5, 10, 28, 21];
let v = 4;
let number = findClosest(array, v); // -> 5
You could do it using jquery's slider by hooking into the slide event (effectively overriding it)... Something like this:
$(function() {
var values = [0, 10, 50, 60, 70, 80, 90, 91, 92, 93, 94, 95, 100];
var slider = $("#slider").slider({
slide: function(event, ui) {
var includeLeft = event.keyCode != $.ui.keyCode.RIGHT;
var includeRight = event.keyCode != $.ui.keyCode.LEFT;
slider.slider('option', 'value', findNearest(includeLeft, includeRight, ui.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;
}
});
Should work for what you describe... I've tested it for dragging with the mouse & using left/right/home/end keys (obviously you'd need to change the left/right to up/down if you want a vertical slider).
Some notes:
Hope that helps.