Dan's Layers Tutorial
3.2  Capturing Keystrokes

The following technique was borrowed from K. Moriyama's JavaScript Games (an amazing page btw, definately check it out!). He figured out an excellent way to capture when selected keys are pressed. And I'll show you how to use it.

To initialize the keyDown and keyUp functions, you can use this chunk of code. It should be at the end of your script so that if someone presses the keys before the page is done loading it won't cause errors.

document.onkeydown = keyDown;
document.onkeyup = keyUp;
document.captureEvents(Event.KEYDOWN | Event.KEYUP);

When a key is pressed down the keyDown() function is called. We want to figure out when someone presses only a certain key. So we capture what key was pressed and put it into a variable "k" and check using an "if" statement if the key was the right one. The following checks if the number 6 key was pressed, and then sets our "stop" variable to 0 and starts the slide:

function keyDown(DnEvents){
	k=DnEvents.which;
	if (k == 54) {		// if 6 is pressed
		stop = 0;
		slide();		
	}
}

When someone releases a key the keyDown() function is called. In this case, when someone releases the number 6 key it sets "stop" to 1 and therefore stops the slide:

function keyUp(UpEvents){
	k=UpEvents.which;
	if (k == 54) {		// if 6 is released
		stop = 1;
	}
}

The slide function is done exactly the same as in the previous example:

function slide() {
	if (stop == 0) {
		document.layers["layer1"].left += 5;
		setTimeout("slide()",30);
	}
}

Here is a quick reference for other "k" numbers:
Keyk Number
Enter13
Space32
048
149
250
351
452
553
654
755
856
957

If you need to know the "k" numbers for letters go to my "k" Number Generator

Since this stuff is just so darn cool I also made an example where you can move the layer in any direction. It's done exactly the same as the example above just with code to handle each direction.


Dan's Layers Tutorial
1.1 Introduction
1.2 Overlapping
1.3 Nesting
1.4 Using JavaScript
2.1 Sliding Layers
2.2 Pre-Built Functions
2.3 Clipping Layers
2.4 Looping Animations
2.5 Changing Images
3.1 Mouse-Click Animation
3.2 Capturing Keystrokes
3.3 Drag and Drop
4.1 Making Demos
4.4 Problems
4.5 Screen Sizes


Copyright © 1997 Dan Steinman. All rights reserved.