简体   繁体   中英

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()
  }
})

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);
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM