Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - keydown() on div not working in Firefox

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.

like image 711
Wayne Koorts Avatar asked Nov 11 '09 20:11

Wayne Koorts


People also ask

What is the difference between keypress () and Keydown ()?

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.

How do you use Keydown?

keydown – on pressing the key (auto-repeats if the key is pressed for long), keyup – on releasing the key.

What does the Keydown () do?

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.

What is difference between Keyup and Keydown in jQuery?

jQuery keyup() Methodkeydown - The key is on its way down. keypress - The key is pressed down. keyup - The key is released.


2 Answers

You need to give the div a tabindex so it can receive focus.

<div id="testdiv" tabindex="0"></div> 
like image 156
Richard Garside Avatar answered Sep 23 '22 20:09

Richard Garside


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

like image 24
Jakob Jenkov Avatar answered Sep 23 '22 20:09

Jakob Jenkov