jQuery - keydown() on div not working in Firefox

Wayne Koorts picture Wayne Koorts · Nov 11, 2009 · Viewed 34.7k times · Source

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.

Answer

Richard Garside picture Richard Garside · Nov 11, 2009

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

<div id="testdiv" tabindex="0"></div>