Categories:

Scripting the keyboard in JavaScript

It was bound to happen- JavaScript discovering your keyboard that is. In this tutorial, I'll show you how JavaScript can be used to detect what key(s) is pressed by the user, and react accordingly.

The relevant event handlers

Before we officially jump in and start possessing your visitor's keyboard, we need to examine first the new keyboard events These events are what make it possible for JavaScript to "react" when a key is pressed:

Keyboard related event handlers
onkeypress:   invokes JavaScript code when a key is pressed
onkeydown:   invokes JavaScript code when a key is held down (but not yet released)
onkeyup:   invokes JavaScript code when a key is has been released after being pressed.

These events can be binded to most elements on the page, though you'll probably be sticking to either the "document" element or form field elements in most cases, as appealing as having your script react to a keypress on a <h1> element is.

Binding a keyboard event to an element

To bind a keyboard event to an element, you can do so either inside your script, or directly inside the element's tag inside your HTML:

<script type="text/javascript">
function alertmsg(){
	alert("You pressed the keyboard inside the document!")
}
document.onkeypress=alertmsg
</script>
<form>
<input type="text" value="Click here, then press a key"
onkeypress="alert('You pressed the keyboard inside this field!')" />
</form>

Now that you know how to bind a keyboard event handler to an element, it's time to get to the meat of things- how to detect what key was pressed, and react accordingly in your script!