I have problem with range slider. I want only this values: 1, 3, 5, 10, but my script isn't working good.
$(function(){
$('#boga').on('input',function(){
var hodnota=$(this).val();
if(hodnota<=5)
$(this).attr("step","2");
else {
$(this).attr("step","5");
}
});
});
var max = 10,
min = 1,
step = 1,
output = $('#output').text(min);
$(".range-slider")
.attr({'max': max, 'min':min, 'step': step,'value': String(min)})
.on('input change', function() {
output.text(this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<output id="output"></output>
<input id="boga" class="range-slider" type="range">
I tried to replace "5" in else with "9", it's working but slider jumps to 1 and after to 10.
You can try this script:
const AVAILABLE_VALUES = [1, 3, 5, 10];
const MAX = AVAILABLE_VALUES[AVAILABLE_VALUES.length - 1],
MIN = AVAILABLE_VALUES[0];
var output = $('#output').text(MIN);
$(function() {
var lastValue = MIN;
$('#boga').on('input keydown', function(event) {
var hodnota = parseInt($(this).val(), 10);
if (event.keyCode) {
// Keyboard navigation
var indexOffset = 0;
switch (event.keyCode) {
case 38:
case 39:
if (hodnota < MAX) {
indexOffset = 1;
}
break;
case 37:
case 40:
if (hodnota > MIN) {
indexOffset = -1;
}
break;
}
hodnota = AVAILABLE_VALUES[AVAILABLE_VALUES.indexOf(hodnota) + indexOffset];
} else if ((AVAILABLE_VALUES.indexOf(hodnota) === -1)) {
// Make dragging more snappy and distinctive
hodnota = lastValue;
}
$(this).val(hodnota);
output.text(hodnota);
lastValue = hodnota;
});
});
$(".range-slider")
.attr({
'max': MAX,
'min': MIN,
'value': String(MIN)
});
If you don't need keyboard navigation you can omit the if (event.keycode) {..} part.
If you don't want to visualize the full length of scale from 1..10 just want the users to select between 1, 3, 5, 10 values you can use the much simpler version:
const AVAILABLE_VALUES = [1, 3, 5, 10];
const MAX = AVAILABLE_VALUES.length - 1,
MIN = 0;
var output = $('#output').text(AVAILABLE_VALUES[MIN]);
$(function() {
$('#boga').on('input', function(event) {
var hodnota = parseInt($(this).val(), 10);
$(this).attr('real-value', AVAILABLE_VALUES[hodnota]);
output.text($(this).attr('real-value'));
});
});
$(".range-slider")
.attr({
'max': MAX,
'min': MIN,
'value': String(MIN),
'real-value': AVAILABLE_VALUES[0]
});
If you have any question please let me know.