views:

1290

answers:

3

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.

+1  A: 

Hi - I don't expect this will work since a div is not something that should receive key events like that. If you placed an <input> inside of that div, and the user pressed a key in the input itself, the event will bubble up to the div and run your function. I'm not 100% sure of what your project is doing so I don't know how to give you more advice, but even though I shouldn't be, I'm kind of surprised that IE is firing off a keydown event on a div.

Jage
+3  A: 

DIVs do not capture keypress/down/up. You'll have to capture it at document level.

$(document).keyup(function(e){   e.keyCode ....  });
Paul Irish
DIVs also do not receive focus.
Josh Stodola
+4  A: 

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

<div id="testdiv" tabindex="0"></div>
Richard
Fantastic! Thank you very much!
Wayne Koorts
Cool. Glad you're sorted.
Richard