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

China☆狼群 提交于 2019-11-27 20:07:06

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.

I'm late but the correct way to ensure the proper event fire now is by using the HTML5 new attribute "contenteditable":

<div id="myEditableDiv" contenteditable="true"> txt_node </div>

classic Js mechanic can then be applied:

var el = document.getElementById('myEditableDiv');
el.addEventListener('keypress', function(e){console.log(e.target.innerText);});
el.addEventListener('keyup', function(e){console.log(e.target.innerText);});
el.addEventListener('keydown', function(e){console.log(e.target.innerText);});

Interesting question. (Here another for you, how to know the div has focus?) As I can see, your div is a popup (its id is dialog). Here you have a workaround:

On popup open:

$("div#modal").data("isOpen", true);

On poup close:

$("div#modal").data("isOpen", false);

Then, the binding:

$('body').keyup(function(e){  //Binding to body (it accepts key events)
   if($("div#modal").data("isOpen")){  //Means we're in the dialog
       if (e.keyCode == 13) //This keyup would be in the div dialog
       {
          $('#next').click(); // Mimicking mouse click to go to the next level.
       }
   }
});

This way, we're mimicking keyup event on the div. Hope this helps. Cheers

PS: Note that you can use #dialog instead of div#dialog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!