Search code examples
javascriptfunctionif-statementaddeventlistenerkeycode

To have a function triggered when up and down key is pressed?


I want to have it so when the up or down key is pressed it triggers different functions. This is my code so far:

window.addEventListener('keypress', function(e) {

    console.log("A Key has been pressed");

    /*Sets "key" variable to be the value of the key code of the key pressed*/
    var key = e.which || e.keyCode;

    /*checks if key pressed is the "up" key*/
    if (key === 38){
            functionOne();
            console.log("Up key was Pressed");
        }

    /*checks if key pressed is the "down" key*/     
    else if (key === 40){
            functionTwo();
            console.log("Down key was Pressed");
        }
    })

The console log displaying "A key has been pressed" activates whenever I press any key apart from the arrow keys, shift, alt, caps, tab and f1 - f12. What could be causing this?

Thank you in advanced.


Solution

  • Use the keyup event instead.

    The onkeypress event is not fired for all keys (e.g. ALT, CTRL, SHIFT, ESC, arrows) in all browsers. To detect only whether the user has pressed a key, use the onkeydown event instead, because it works for all keys.

    window.addEventListener('keyup', function(e) {
    var key = e.which || e.keyCode;
        console.log(key);
        if (key === 38){
            console.log("Up key was Pressed", key );
        }    
        else if (key === 40){
            console.log("Down key was Pressed", key );
        }
        e.preventDefault();
    })