views:

5974

answers:

4

The following works fine on IE6, IE7, and chrome. Not working on ff 3.0.7.

<html><head>
<script src="prototype.js" type="text/javascript" ></script>
<script type="text/javascript">
Event.observe(window, 'load', 
    function(){
     Event.observe(document.body, 'keydown', myEventHandler);
     alert('window load');
    });
function myEventHandler(evt) {
    alert(evt);
}
</script>
</head>
<body >
<input type="text" /><br><br>
</body></html>

EDIT: By "not working" I mean myEventHandler is not firing in firefox.

EDIT2: Furthermore, it works fine when focus is on the input element. I want it fire for all keydowns.

A: 

Try to wrap the input with a form element. If that doesn't help, warp it in a div and attach your handler to the div.

Aaron Digulla
Wrapping in a form made no change. Wrapping in a div and attaching the handler to the div broke IE and Chrome without fixing FF.Note that I want the event handler to fire regardless of whether focus is in the input element.
Chloraphil
+2  A: 

I also found that my keydown events weren't firing in Firefox for similar code. In my case, I don't need to use anything other than Safari and Firefox, so I have not tested this on IE. Nevertheless, observing 'document' rather than 'document.body' seemed to work:

document.observe('dom:loaded', function() {
    Event.observe(document, 'keypress', function(evt) {
       alert("In Keypress Function");
    });
});

Now, I realize this is observing keypress, not keydown. AFAIK, keypress is generated right after keydown.

Jarret Hardie
+4  A: 

I have no idea why your code doesn't work, but it's overly complicated - this should do the trick:

document.observe('keydown', myEventHandler);

There's no need to wait for load as document is available immediately.


Your code doesn't work because not all key events originate within a document's body element. Opera has issues similar to the ones in Firefox, but the originating element seems to additionally depend on the placement of the mouse cursor.

Anyway, the fix is to just catch the events at document level, because as long as no one stops them from doing so, all DOM events will bubble up to document eventually.

Christoph
Thanks I didn't know you could do it that way. I just $('id').observe('keypress', function(t){if(e.keyCode==13){getTypes()}}); to make pushing enter run a function on my textbox.
hamstar
A: 

btw, for tab, esc, and similar, you need to use keyup, not keypress. At least for Safari, took me quite a while to figure that one out.

See for yourself by adding this line: alert ("Key :" + evt.keyCode); in the anon. function. Only glyphs respond.

--Dave

the Hampster