25

Is there a way to listen to keyboard events on a DIV element?

My code:

​<div id="div" style="height:50px" class="ui-widget-content"></div>
<input id="input">​​​​​​​​​​​​​​

​$('#div,#input').keyup(function(event){
    console.log(event.keyCode);
});​​​​​​

Actually, the code triggers only for the input, can I handle it for the div?

ilyes kooli
  • 11,766
  • 13
  • 49
  • 79
  • 1
    Possible duplicate of http://stackoverflow.com/questions/148361/how-can-i-give-keyboard-focus-to-a-div-and-attach-keyboard-event-handlers-to-it/148444#148444 as mentioned in one of the answers.. – Selvakumar Arumugam May 23 '12 at 15:02
  • Does this answer your question? [How can I give keyboard focus to a DIV and attach keyboard event handlers to it?](https://stackoverflow.com/questions/148361/how-can-i-give-keyboard-focus-to-a-div-and-attach-keyboard-event-handlers-to-it) – mikemaccana Mar 24 '21 at 15:48

4 Answers4

48

You can add a tabindex in that div to catch keyboard events like this

<div id="div" style="height:50px" class="ui-widget-content" tabindex="0"></div>

Like answered here.

Working Fiddle

Reference

Community
  • 1
  • 1
Prasenjit Kumar Nag
  • 13,321
  • 3
  • 43
  • 57
5

Add a tabindex and it should work

<div id="div" style="height:50px;" class="ui-widget-content" tabindex="1"></div>

DEMO

Selvakumar Arumugam
  • 78,145
  • 14
  • 119
  • 133
2

you need to add a tabindex to the div.

see this fiddle:

http://jsfiddle.net/w2Y4d/1/

mkoryak
  • 55,751
  • 59
  • 197
  • 255
0

Why not place the input inside the div and then simply find $('#input').closest('div') ?

Otherwise, if your example is a pattern of how your inputs relate to your divs then simply $('#input').prev() ?

Brian Scott
  • 9,043
  • 6
  • 44
  • 68