Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling `stepDown` or `stepUp` doesn't trigger `change` or `input` event on range input

When calling stepDown and stepUp on a <input type='range'>, the input or change events are not being triggered.

Here's a code sample of the issue in action:

<p>J and K move slider left and right but aren't triggering event. 
Using mouse though successfully updates label.</p>

<p>Label isn't updating on keypress which is 
calling <code>stepDown()</code> and <code>stepUp()</code></p>

<input type='range' id='number' step='10'/> 
<label id='value'>50</label>
const numberEl = document.getElementById('number')
const valueEl = document.getElementById('value')

// Same issue is present when listening to 'change'
numberEl.addEventListener('input', (event) => {
  valueEl.innerText = event.target.value
})

document.addEventListener('keydown', (event) => {
  if (event.code === 'KeyJ'){
    numberEl.stepDown()
  }
  if (event.code === 'KeyK'){
    numberEl.stepUp()
  }
})
like image 281
Ricky Brooks Avatar asked Jan 31 '26 00:01

Ricky Brooks


1 Answers

You'll have to trigger the change event in the key down event manually since onchange only fires when the element loses focus

  ...

  if (event.code === 'KeyJ'){
    numberEl.stepDown()
  }
  if (event.code === 'KeyK'){
    numberEl.stepUp()
  }
  
  const ev = new Event('change');
  numberEl.dispatchEvent(ev);
...
like image 67
markfila Avatar answered Feb 01 '26 14:02

markfila



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!