jQuery - keydown() on div not working in Firefox

Viewed 36242

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.

9 Answers

Basically:

Call yourElement.focus() after setting the 'onkeydown' event... Example:

div.onkeydown = (e) {
   alert(e.key)
   // or whatever
}

div.focus() // Add this

This should work:

$(document).on("keydown", "#mydiv" function(e) {
    alert('Pressed '+ e.keyCode);
});

$('#mydiv').attr('tabindex', "0")
$('#mydiv').focus();
Related