Search code examples
javascripteventskeycodearrow-keys

How can I handle ArrowKeys and < (Greater Than) in a Javascript function? Which event and which code (charCode Or keyCode)?


How can I handle ArrowKeys and < (Greater Than) in a Javascript function? Which event and which code (charCode Or keyCode)?

I am very confused how to do this. I have read this link very carefully, Events and keyCode+charCode, but I could not find any solution for my scenario.


Solution

  • Using event.keyCode is sufficient. You only need to browser compatibility issues with regard to obtaining the key event into account.

    Here's a basic kickoff example which captures arrow keys, copy'n'paste'n'run it:

    <!DOCTYPE html>
    <html lang="en">
        <head>
            <title>SO question 3181648</title>
            <script>
                document.onkeydown = function(e) {
                    e = e || event; // "real browsers" || IE6/7.
                    switch (e.keyCode) {
                        case 37: alert('left'); break;
                        case 38: alert('up'); break;
                        case 39: alert('right'); break;
                        case 40: alert('down'); break;
                    }
                }
            </script>
        </head>
        <body>
           <p>Press one of the arrow keys.</p> 
        </body>
    </html>
    

    Note that attaching events is better to be done this way or using jQuery.

    For capturing the pressed characters like <, have a look at Tim's answer.