Kichu
Kichu

Reputation: 3267

Checking Keyboard or Mouse events are done in a Div

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

Answers (2)

yodog
yodog

Reputation: 6252

The div must have focus.
Here is how you do it:

1- Tabindex:

// JQ
$("#divID")
    .attr("tabindex", "0")
    .keydown(function(){ /* ... bla bla bla ... */ return false; });

Or

// JS
<div id="divID"
     width="500px"
     height="500px"
     tabindex="1">
</div>

2- setting contentEditable to true:

$("#divID").attr("contentEditable", "true")

Or

$("#divID")[0].contentEditable = true;

Links:

How do I give an HTML canvas the keyboard focus using jquery?
How do you set focus to the HTML5 canvas element?

Upvotes: 1

Tobias Krogh
Tobias Krogh

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

Related Questions