ilyes kooli
ilyes kooli

Reputation: 12053

How to bind keyboard events to div elements?

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?

Upvotes: 26

Views: 25990

Answers (4)

Prasenjit Kumar Nag
Prasenjit Kumar Nag

Reputation: 13471

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

Upvotes: 52

mkoryak
mkoryak

Reputation: 57998

you need to add a tabindex to the div.

see this fiddle:

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

Upvotes: 2

Brian Scott
Brian Scott

Reputation: 9381

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() ?

Upvotes: 0

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79850

Add a tabindex and it should work

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

DEMO

Upvotes: 5

Related Questions