Key Events

When you press any key on your keyboard, the browser will register them through a series of events. The events are keydown, keypress and keyup.

  1. keydown: when the key is first pressed.
  2. keypress: if the pressed key is not a modifier key alt, shift, ctrl, meta (Command on Mac) this event is fired.
  3. keyup: when the key is released.

The events will fire in this order when the key is pressed and immediately released. If the user holds down a key, auto repeat normally kicks in. During auto repeat, the keydown and keypress event will keep firing in sequence until the key is released, at which point keyup will fire.

  1. keydown
  2. keypress
  3. keydown
  4. keypress
  5. ...keeps going until released
  6. keyup

To find out which key the user has pressed, we can inspect the Event.key property of the event object passed to the handler. Event.key will return a string value of the actual character that is pressed. If the user pressed the "j" key only, Event.key will show "j", if the user pressed the "j" key while in capitalized mode or holding down the "shift" key at the same time, Event.key will show "J".

We can build a simple program to display the key being pressed.

<p>Press a key and find out what key is pressed</p>
<div id="log"></div>
var log = document.body.querySelector('#log');
window.addEventListener('keydown', function(event) {
  var p = document.createElement('p');
  p.innerHTML = 'keydown: key="' + event.key + '"';
  log.appendChild(p);
});

Try it on Repl

You will notice arrow keys are represented with "Arrow" then the direction, such as "ArrowUp". Modifier keys such as shift is represented as "Shift".

To find out whether any of the modifier keys are being pressed while a key event is fired, we can inspect each of the modifier key properties in the Event object.

  • Event.ctrlKey
  • Event.shiftKey
  • Event.altKey
  • Event.metaKey

If any of the modifier keys are held down during a key event, their corresponding property will return true.

We can modify the previous program slightly to show active modifier keys.

var log = document.body.querySelector('#log');
window.addEventListener('keydown', function(event) {
  var p = document.createElement('p');
  var message = 'keydown: key="' + event.key + '"';
  var modifiers = [];
  if (event.ctrlKey) {
    modifiers.push("Control");
  }
  if (event.shiftKey) {
    modifiers.push("Shift");
  }
  if (event.altKey) {
    modifiers.push("Alt");
  }
  if (event.metaKey) {
    modifiers.push("Meta");
  }
  if (modifiers.length > 0) {
    message += ' Modifiers="' + modifiers.join(", ") + '"';
  }
  p.innerHTML = message;
  log.appendChild(p);
});

Try it on Repl

Please Move Pac Man

Okay, it's time for a little bit of fun. We are going to draw a little Pac Man on screen, then use arrow keys to try and move it. If you recall the "blob that follows the mouse pointer" demo, this one is very similar. Lets start by drawing a little Pac Man.

<div id="pacman" style="top: 0; left: 0;">
</div>
#pacman {
  width: 0px;
  height: 0px;
  border-right: 30px solid transparent;
  border-top: 30px solid yellow;
  border-left: 30px solid yellow;
  border-bottom: 30px solid yellow;
  border-top-left-radius: 30px;
  border-top-right-radius: 30px;
  border-bottom-left-radius: 30px;
  border-bottom-right-radius: 30px;
  position: fixed;
}

To move Pac Man with our arrow keys, we need to listen for the keydown event. Then change the top or left value of Pac Man based on the arrow key pressed.

window.addEventListener('keydown', function(event) {
  var pacman = document.getElementById('pacman');

  switch (event.key) {
    case "ArrowUp":
      pacman.style.top = (parseInt(pacman.style.top, 10) - 2) + "px";
      break;
    case "ArrowDown":
      pacman.style.top = (parseInt(pacman.style.top, 10) + 2) + "px";
      break;
    case "ArrowLeft":
      pacman.style.left = (parseInt(pacman.style.left, 10) - 2) + "px";
      break;
    case "ArrowRight":
      pacman.style.left = (parseInt(pacman.style.left, 10) + 2) + "px";
      break;
  }
});

Try it on Repl

Creating an actual playable game would require a lot more than this. You have to think about how to draw the map, store positions of the characters. What happens when characters collide or interact, etc. A lot more to do with programming and program architecture than manipulating the DOM.

We built a Pong game a while ago and you can check it out here.

results matching ""

    No results matching ""