Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to grab keyboard events on an element which doesn't accept focus?

I know that for handling keyboard events in an input field you can use:

$('input').keyup(function(e){ var code = e.keyCode // and 13 is the keyCode for Enter }); 

But, now, I have some div and li elements, and I don't have a form element, and none of my elements are considered to be form elements and none of them accept focus or tab and stuff like that.

But now I need to handle the keyup (or keydown, or keypress, doesn't matter) event in a div element. I tried:

$('div#modal').keyup(function(e){    if (e.keyCode == 13)    {       $('#next').click(); // Mimicking mouse click to go to the next level.    } }); 

But the problem is, it doesn't work. What should I do?

like image 419
Saeed Neamati Avatar asked Jul 09 '11 06:07

Saeed Neamati


People also ask

What event is specific to the keyboard?

There are three keyboard events, namely keydown , keypress , and keyup .

How do I make a div keyboard focusable?

You can make it focusable by adding a tabindex=0 attribute value to it. That will add the element to the list of elements that can be focused by pressing the Tab key, in the sequence of such elements as defined in the HTML document.


1 Answers

A div by default cannot be given focus. However, you can change that by adding a tabindex attribute to the div:

<div tabindex="0" id="example"></div> 

You can then give the div focus, and also blur it with the hover event:

$("#example").hover(function() {     this.focus(); }, function() {     this.blur(); }).keydown(function(e) {     alert(e.keyCode); }); 

When the div has focus, it will accept keyboard events. You can see an example of this working here.

like image 51
James Allardice Avatar answered Sep 24 '22 01:09

James Allardice