Search code examples
javascriptjquerykeypress

Bind arrow key presses to a certain div no matter what is in focus


I have an html5 video canvas, I would like it to react to all key presses, but especially arrow key presses no matter what is in focus. How would I go about doing this?


Solution

  • Leverage event bubbling. Key codes for arrow keys are 37-40. Now, when any page element recieves a keydown event, it will bubble to the window object, where it will be handled. At that point, the key will be checked to see if it is an arrow key (you need to fill in the cases as you desire).

      window.addEventListener("keydown", function(evt){
         alert(evt.which);
         switch(evt.which){
           case 37:
              alert("Left arrow key pressed!");
              break;
           case 38:
              alert("Up arrow key pressed!");
              break;
           case 39:
              alert("Right arrow key pressed!");
              break;              
           case 40:
              alert("Down arrow key pressed!");
              break; 
           default:
           break;
         }
      });
    

    See: https://jsfiddle.net/avbto94z/8/ for example with canvas. Note that there are several other elements on the page. Click into or use the tab key to move the focus to elements besided the canvas and press keys on the keyboard.