prototype/javascript - firefox not firing keypress/keydown event unless focus is in textbox

16,474

Solution 1

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.

Solution 2

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.

Share:
16,474
Chloraphil
Author by

Chloraphil

Updated on July 01, 2022

Comments

  • Chloraphil
    Chloraphil about 2 years

    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.