Next page | Contents page |

Keyboard events

There are two events we could listen for: "keydown" and "keyup". It is likely that we only need the first of these. I find it best to add the listener to the document object. Otherwise we would need to ensure the focus is on the right element for it to work. So in run() put


	document.addEventListener("keydown", handleKeydown);

The event passed to the listener by the system has a property key - a string representing the key that was pressed. In many cases that will be a single character but some keys, such as arrows, have descriptive strings. A full list of those can be found on MDN.

The listener function will typically need a switch statement to act on each of the keys we need to recognise:


	switch (e.key)
	{
	  case "w":
	  case "ArrowUp": forward(); return;
	  case "a":
	  case "ArrowLeft": left(); return;
	  case "s":
	  case "ArrowDown": back(); return;
	  case "d":
	  case "ArrowRight": right(); return;
	  case "z": if (e.ctrlKey) undo(); return;
	}

Some people use keys WASD instead of arrows. Maybe some keyboards do not have arrows so the example allows alternatives.

Notice the event property for testing whether the Ctrl key is also down. There are similar properties for Shift and Alt.

If using arrow keys it is worth adding this as the first line of the listener function, to avoid the default action of such keys which is to scroll the canvas within the window:


	e.preventDefault();
There is a problem if a key is held down so it automatically repeats. Recall the event pattern:

	event  ->  our function  ->  refresh screen  ->  stop

MS Edge and (so I'm told) all browsers based on Chromium don't bother to refresh screen if the key is immediately causing a repeat event. I consider this to be a bug in those browsers. It is a problem in some games because by the time the key is released the display can have changed far more than the user expects. Firefox works correctly though. (As of August 2024.)

Next page | Contents page |