Hick Hick - 10 months ago 85
Javascript Question

How to take keyboard input in JavaScript?

I want to take keyboard input in JavaScript, where arrow keys, when pressed, will result in the change in shape of a particular shape. How do I take the input of any of the keys in JavaScript?

Answer Source

You can do this by registering an event handler on the document or any element you want to observe keystrokes on and examine the key related properties of the event object.

Example that works in FF and Webkit-based browsers:

document.addEventListener('keydown', function(event) {
    if(event.keyCode == 37) {
        alert('Left was pressed');
    else if(event.keyCode == 39) {
        alert('Right was pressed');