4

I must be losing it, I can't get the keydown event to work:

I tried:

$('#container').keydown(function() {
            console.log("down");
            alert('down');
    });

Also tried:

$('#container').on('keydown',function() {
            console.log("down");
            alert('down');
    })

http://jsfiddle.net/foreyez/mwptttdv/

Shai UI
  • 50,568
  • 73
  • 204
  • 309
  • 3
    Because only form elements (almost) are focusable, and only focused elements can detect keyboard events. You can add `tabindex="0"` to the `div` [to gain focus](http://jsfiddle.net/rvL64c7j/) to it. – Teemu Mar 31 '15 at 16:41
  • ahhh answered same time as me. Add your answer as an answer. Deleting mine. – Ted Mar 31 '15 at 16:44
  • 1
    @Ted I'm searching for a dup, there must be a one ... [Here](http://stackoverflow.com/questions/3759339/keypress-on-a-div-tag), and [another](http://stackoverflow.com/questions/3149362/capture-key-press-or-keydown-event-on-div-element). – Teemu Mar 31 '15 at 16:45

1 Answers1

6

You actually can get the browser to recognize the keydown on the div if you give it a tabindex attribute:

<div id='container' tabindex="1"></div>

jsFiddle example

j08691
  • 204,283
  • 31
  • 260
  • 272