Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can i track arrow keys in Chrome and IE?

Im using foloowing code to track key events

oEvent=window.event || oEvent;
    iKeyCode=oEvent.keyCode || oEvent.which;alert(iKeyCode);

its giving me alerts in firefox but not in IE and chrome. Its giving me all the other keyborad characters but not esc key and arrow keys.

How can i detect esc key and arrow keys in chrome and IE using javascript??

like image 721
developer Avatar asked Jun 03 '11 12:06

developer


People also ask

How do I navigate with arrow keys in Chrome?

Click on the three vertical dots and select Settings. Go to Advanced > Accessibility. Turn off Navigate pages with a text cursor.

Where are arrow keys located?

The function keys (F1 F2 etc) The numeric keypad (1 2 3 etc) on the right of the keyboard. Cursor control keys (the arrows) on the right of the keyboard. A number of specially defined keys (Enter, Shift, Windows key etc)


1 Answers

You don't really need JQuery, though it does make your code shorter.

You will have to use the keyDown event, keyPress will not work in old versions of IE for the arrow keys.

There is a full tutorial here that you can use, see the example with arrow keys close to the bottom of the page: http://www.cryer.co.uk/resources/javascript/script20_respond_to_keypress.htm

Here's some code I used, a bit simplified since I had to handle repeated keypresses with buffering:

document.onkeydown = function(event) {
     if (!event)
          event = window.event;
     var code = event.keyCode;
     if (event.charCode && code == 0)
          code = event.charCode;
     switch(code) {
          case 37:
              // Key left.
              break;
          case 38:
              // Key up.
              break;
          case 39:
              // Key right.
              break;
          case 40:
              // Key down.
              break;
     }
     event.preventDefault();
};
like image 179
Gaurav Avatar answered Oct 23 '22 23:10

Gaurav