Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is the range slider step being applied twice?

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' />

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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'/>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading