O'Reilly logo

JavaScript & DHTML Cookbook by Danny Goodman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Reading Which Noncharacter Key Was Pressed

NN 6, IE 4

Problem

You want to initiate a script action based on whether the user pressed one of the noncharacter keyboard keys.

Solution

Use the onkeydown or onkeyup event handler to read the code number associated with the noncharacter key. You can read this value from the event object's keyCode property in IE 4 or later and Netscape 6 or later.

The following function (which also invokes the getElementStyle( ) function from Recipe 11.12) moves an absolute-positioned element in five-pixel increments in the direction of the keyboard arrow key that the user presses:

function handleArrowKeys(evt) {
    evt = (evt) ? evt : ((window.event) ? event : null);
    if (evt) {
        var top = getElementStyle("moveableElem", "top", "top");
        var left = getElementStyle("moveableElem", "left", "left");
        var elem = document.getElementById("moveableElem");
        switch (evt.keyCode) {
            case 37:
                elem.style.left = (parseInt(left) - 5) + "px";
                break;    
            case 38:
                elem.style.top = (parseInt(top) - 5) + "px";
                break;    
            case 39:
                elem.style.left = (parseInt(left) + 5) + "px";
                break;    
            case 40:
                elem.style.top = (parseInt(top) + 5) + "px";
                break;    
         }
    }
}
   
document.onkeyup = handleArrowKeys;

This example uses the onkeyup event handler because the onkeydown event is broken in Netscape 7 (and neither onkeyup nor onkeydown works in Netscape 6.x). This is too bad: when you use onkeydown in IE, holding the key down until it goes into auto-repeat causes the onkeydown event to fire repeatedly, moving ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required