• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

9. Managing Events > 9.9. Reading Which Noncharacter Key Was Pressed

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";
        ....

PREVIEW

                                                                          

Not a subscriber?

Start A Free Trial


  
  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint