🏠 Games Tutorials Dev blog JS code golf Other projects

Keys pressed

September 2013 - january 2022

A way to know at any moment if a key is being pressed, in just 44 bytes.

k={};onkeydown=onkeyup=e=>k[e.key]=e.type[5]

To use it, test k[n] (where n is the name of a keyboard key. Ex: "a", "A", "1", ".", "Space", "Control", etc).
k[n] is truthy when the key is pressed, and falsy when it's not pressed (or has been released).

Source code

// Initialize the global k (the array representing the keys currently pressed).
// Also works with k = [].
k = {};

// Add two event handlers to the window object:
// window.onkeydown and window.onkeyup.
// They don't need the "window." prefix (it's implicit)
// And they both get the same callback function
onkeydown = onkeyup = function(e){

  // On keydown, e.type == "keydown", and e.type[5] == "w" (truthy)
  // On keyup, e.type == "keyup", and e.type[5] == undefined (falsy)
  // !! converts e.type[5] to a boolean. It can be removed but it's a little dirtier.
  // e.key can be replaced with e.keyCode (in that case, each key is mapped to a given number)
  
  k[e.key] = !!e.type[5];

}


Demo: k is displayed below. Press any key to see it change.
k = { }