Home > database >  Why is the range slider step being applied twice?
Why is the range slider step being applied twice?

Time:12-30

I have a range slider that you can move up with the right arrow key on a keyboard or grab and move. The step over 36 is 3 and the step under 36 is 1. This works perfectly on their own. However, if you were to move the slider manually and then use the keydown event, the step is being applied twice to the slider. How can I get the step to always just apply once?

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

document.addEventListener('keydown', function(e) {
  console.log(rangeSlider.value, '1');
  // Update the step size based on the current value of the range slider
  if (rangeSlider.value >= 36) {
    var step = 3;
  } else {
    var step = 1;
  }
  // Set the step size of the range slider to the calculated value
  rangeSlider.setAttribute("step", step);

  if (e.keyCode == 39) { //right
    // Increment the value of the range slider by the step size
    rangeSlider.value = parseInt(rangeSlider.value)   parseInt(step);
    console.log(rangeSlider.value, '2');
  }
});
<input type='range' min='0' max='84' value='0' id='range-slider' class='slider' />

CodePudding user response:

You forgot to cancel the original movement with e.preventDefault()

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

document.addEventListener('keydown', function(e) {
  console.log(rangeSlider.value ,'1');
  // Update the step size based on the current value of the range slider
  if (rangeSlider.value >= 36) {
    var step = 3;
  } else {
    var step = 1;
  }
  // Set the step size of the range slider to the calculated value
  rangeSlider.setAttribute("step", step);

  if (e.keyCode == 39) { //right
    // Increment the value of the range slider by the step size
    e.preventDefault();
    rangeSlider.value = parseInt(rangeSlider.value)   parseInt(step);
    console.log(rangeSlider.value ,'2');
  }
});
<input type='range' min='0' max='84' value='0' id='range-slider' class='slider'/>

  • Related