Search code examples
javascripthtmlsliderrangeslider

Why is Range Slider doubling the step when clicked here?


I have a range slider in which the step is 1 before hitting 36 and 3 after going over 36. I control the slider with the left and right arrow keydown functions on a keyboard. It works perfectly, except for when you click or drag the slider and then try and use the keydowns. If you do that, you'll notice the step get applied twice.

Through some work I have found that the step itself doesn't double, but for some reason the step is being subtracted from the rangeSlider.value twice instead of once. I am totally out of ideas on how to fix this. You'll notice after clicking anywhere on the slider and then using the keydown the 'here2' console log will increase by double the step and I'm not sure why.

How can I get the rangeSlider.value to increase by the correct step after the slider is clicked and then the keydown events are received?

 var rangeSlider = document.getElementById('range-slider');

console.log(rangeSlider.value);


 document.addEventListener('keydown', function(e) {
// If the value of the slider is greater than 36, set the step size to 3
if (rangeSlider.value >= 36) {
  var step = 3;
} else {
  var step = 1;
}
 rangeSlider.setAttribute("step", step)

 if (e.keyCode == 39) { //right
console.log(rangeSlider.value, 'here')
    rangeSlider.value = parseInt(rangeSlider.value) + parseInt(step);
  console.log(parseInt(rangeSlider.value), 'here2')

  } else if (e.keyCode == 37) { //left
console.log(rangeSlider.value, 'here')
    rangeSlider.value = parseInt(rangeSlider.value) - parseInt(step);
console.log(parseInt(rangeSlider.value), 'here2')
  }})
<input type='range' min='0' max='84' value='0' id='range-slider' class='slider'/>


Solution

  • Pressing an arrow key triggers a built-in event handler of the element when it has focus: it increments the value without needing additional code. Your additional code increments it further. You only need to change the step size. If you are looking for it to increment when it doesn't have focus, use the keydown event to set the focus.

    document.addEventListener('keydown', function(e) {
      // If the value of the slider is greater than 36, set the step size to 3
    
      if ((e.keyCode == 39) ||  (e.keyCode == 37)) {
      rangeSlider.focus();    
      if (rangeSlider.value >= 36) {
        var step = 3;
        } else {
        var step = 1;
        }
       rangeSlider.setAttribute("step", step);
       console.log(rangeSlider.value);
       }
     })