I have the following example code, which should pop up an alert when the div is in focus and a key is pressed. This does what I expect in IE 7, but not in Firefox 3.5.5. What am I doing wrong?
<html> <head> <title>JS test</title> <script type="text/javascript" src="jquery-1.3.2.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("#testdiv").keydown(function(event) { alert("Pressed " + event.keyCode); }); }); </script> <style type="text/css"> #testdiv { width: 50; height: 50; background-color: red; } </style> </head> <body> <div id="testdiv"></div> </body> </html>
EDIT: I've just tried replacing keydown
with keypress
and keyup
and those don't work either. Incidentally, I also made sure that my "Find as you type" setting is turned off just in case.
keydown – fires when any key is pressed down, fires first, and always before the browser processes the key (e.g. inserting text, moving focus, etc). keypress – fires when a key that produces a character value is pressed down, fires after keydown , and before the browser processes the key.
keydown – on pressing the key (auto-repeats if the key is pressed for long), keyup – on releasing the key.
The keydown event is sent to an element when the user presses a key on the keyboard. If the key is kept pressed, the event is sent every time the operating system repeats the key. It can be attached to any element, but the event is only sent to the element that has the focus.
jQuery keyup() Methodkeydown - The key is on its way down. keypress - The key is pressed down. keyup - The key is released.
You need to give the div a tabindex so it can receive focus.
<div id="testdiv" tabindex="0"></div>
I got the above to work in Firefox, like this:
$('#domainTableDiv').keydown(function(e) { alert(e.type + " button(" + e.which + ") ctrl(" + e.metaKey + ") alt(" + e.altKey + ") shift(" + e.shiftKey + ")" ); }); $('#domainTableDiv').focus();
Once the DIV has focus set on it explicitly, key events fire just fine in Firefox 4.0.1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With