Reputation: 2849
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.
Upvotes: 3
Views: 16593
Reputation: 906
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
Upvotes: 0
Reputation: 169583
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.
Upvotes: 7
Reputation: 97932
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.
Upvotes: 3
Reputation: 328594
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.
Upvotes: 0