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

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.

Leave a Comment