)
}
}
)
(
}
{
)
)
(
)
(
(
{
}
)
(
)
}
)
)
{
(
(
)
)
}
)
(
}

Easy Keyboard Controls JavaScript

  1. const Key = {
  2.   LEFT: 37,
  3.   UP: 38,
  4.   RIGHT: 39,
  5.   DOWN: 40,
  6.   disabled: false
  7. }
  8.  
  9. const keyDown = {}
  10.  
  11. function setupKeys() {
  12.   const alph = 'abcdefghijklmnopqrstuvwxyz'.split('')
  13.   const keys = {}
  14.   const aKey = 65
  15.   alph.forEach((letter, i) => {
  16.     const idx = aKey + i
  17.     keyDown[idx] = false
  18.     Key[letter.toUpperCase()] = idx
  19.   })
  20.  
  21.   document.addEventListener('keydown', e => {
  22.     if (!Key.disabled) {
  23.       keyDown[e.which] = true
  24.     }
  25.   })
  26.  
  27.   document.addEventListener('keyup', e => {
  28.     keyDown[e.which] = false
  29.   })
  30. }
  31.  
  32. setupKeys()
  33.  
  34. // later:
  35.  
  36. function loop() {
  37.   if (keyDown[Key.LEFT]) {
  38.     console.log('left')
  39.   }
  40.   if (keyDown[Key.UP]) {
  41.     console.log('up')
  42.   }
  43.   if (keyDown[Key.C] || keyDown[Key.D]) {
  44.     console.log('c or d key')
  45.   }
  46.   requestAnimationFrame(loop)
  47. }
  48. loop()
  49.  
  50. const info = document.createElement('div')
  51. info.innerHTML = 'click to give focus - then use C, D or LEFT keys.'
  52. document.body.appendChild(info)

Use a desktop and go into fullscreen when using the quick editor to see this in action…

This is a good way to deal with more complex key controls. event.which and event.key often won’t cut it, especially with key combos and different systems.

// javascript // keys // tricks // ui
snippet.zone ~ 2021-24 /// {s/z}