Capture key press (or keydown) event on DIV element

Lalchand picture Lalchand · Jun 30, 2010 · Viewed 119.2k times · Source

How do you trap the keypress or key down event on a DIV element (using jQuery)?

What is required to give the DIV element focus?

Answer

helle picture helle · Jun 30, 2010

(1) Set the tabindex attribute:

<div id="mydiv" tabindex="0" />

(2) Bind to keydown:

 $('#mydiv').on('keydown', function(event) {
    //console.log(event.keyCode);
    switch(event.keyCode){
       //....your actions for the keys .....
    }
 });

To set the focus on start:

$(function() {
   $('#mydiv').focus();
});

To remove - if you don't like it - the div focus border, set outline: none in the CSS.

See the table of keycodes for more keyCode possibilities.

All of the code assuming you use jQuery.

#