Reputation: 3267
How can I check if a keyboard or mouse event is done inside of a div?
Once I check the onmousemove() event of a div it works but onkeyup, onkeypress etc are not working for the div.
What is the reason for that?
<div onmousemove="alert(1);" onkeypress="alert(2);">
Here alert(1) will be displayed but alert(2) is not displayed.
Upvotes: 2
Views: 437
Reputation: 6252
The div must have focus.
Here is how you do it:
// JQ
$("#divID")
.attr("tabindex", "0")
.keydown(function(){ /* ... bla bla bla ... */ return false; });
Or
// JS
<div id="divID"
width="500px"
height="500px"
tabindex="1">
</div>
$("#divID").attr("contentEditable", "true")
Or
$("#divID")[0].contentEditable = true;
How do I give an HTML canvas the keyboard focus using jquery?
How do you set focus to the HTML5 canvas element?
Upvotes: 1
Reputation: 3942
check out this fiddle. you cannot fire key events on an element that does not allow you to focus and input... it might be possible with contenteditable
but I am not sure... when you do a keypress inside of the input of the fiddle the onkeypress of the div is triggering
EDIT: I just discovered that you can also set up a tabindex="0" on the div and therefore make it focussable (see the updated new fiddle) then no input is needed BUT it interferes when using TAB key to walt through focussable elements
Upvotes: 2