Search code examples
htmldomw3c

DOM keydown event with a long key press


I want to be notified when a key is pressed down, and then not notified until it is released. Is this possible?

When the key is held down, listening for keydown appears to repeatedly trigger the onkeydown callback.


Solution

  • You can set a flag, and reset on key up.

    let isPressed = false;
    
    document.addEventListener('keydown', () => {
      if (!isPressed) {
        isPressed = true;
        onDown();
      }
    })
    
    document.addEventListener('keyup', () => {
      isPressed = false;
      console.log('Up.')
    })
    
    function onDown() {
      console.log('Pressed')
    }