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,959
  • 14
  • 50
  • 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

51

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,391
  • 3
  • 45
  • 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
  • 79,297
  • 15
  • 120
  • 134
2

you need to add a tabindex to the div.

see this fiddle:

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

mkoryak
  • 57,086
  • 61
  • 201
  • 257
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,221
  • 6
  • 47
  • 68