182

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?

mikemaccana
  • 110,530
  • 99
  • 389
  • 494
Lalchand
  • 7,627
  • 26
  • 67
  • 79

3 Answers3

365

(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.

#
helle
  • 11,183
  • 9
  • 56
  • 83
  • 59
    +1 tabindex is the key point here to make the div 'selectable'. JQuery not necessary, the same thing works with Angular as well as (I suppose) with plain javascript events. – Jukka Dahlbom Feb 12 '14 at 10:57
  • 4
    What's the browser support for this? – knownasilya Nov 19 '14 at 20:06
  • 39
    tabindex is a key part, but do not set it to any value other than "0". Making it anything above 0 is going to mess up screen readers for visually impaired users (it will skip everything on the page and go straight to any tabindex above 0). tabindex="0" makes it "tabbable." you can have infinite elements with tabindex="0" – zonabi Feb 29 '16 at 18:26
  • 2
    Works with
     as well!
    – dfmiller Mar 15 '16 at 15:45
  • 2
    Excellent! I was missing the tabindex attribute, maybe because DIV's can't receive focus unless they have a tabindex. Thanks man! Saved my life! EDIT: works with React as well – Vinícius Negrão Feb 16 '17 at 19:31
  • 1
    As of jQuery 3.0, .bind() has been deprecated. It's should use .on('keydown',.. instead off .bind('keydownm.. http://api.jquery.com/bind – Mohamad Hamouday Nov 26 '18 at 11:13
  • 1
    It's worth noting that while `keydown` works just fine, `keypress` does not. (At least in my situation with an `
  • ` on Chrome.)
  • – jlh Feb 10 '20 at 12:43
  • 1
    One helle of a good answer! – Jonah Jan 16 '22 at 16:32
  • 1
    Note the javascript attribute is `tabIndex` not `tabindex` (capital i). – Friedrich -- Слава Україні Nov 07 '22 at 17:36