views:

227

answers:

4

I want to respond to the user hitting the enter key, which I can do, however I dont want to respond to the event when the user hits the enter key and the focus is on the address bar. I can not figure out how to prevent my key event handler from executing when the focus is in the address bar.

Note: The page refreshes, but my handler is called first.

Please dont tell me not to do the action when the focus is in the address bar, I know that, tell me how to check that the focus is not in the address bar, thanks

OK, i got it, it the keyup event, not keydown, thats causing this, thanks for the help

+3  A: 

If the user's focus is on the address bar and the user hits the Enter key, you will not be able to prevent it, and your event handler should not even run (though the page will reload).

Brian Ramsay
+1  A: 

in prototype you can attach keylisteners to the document

Event.observe(document, 'keypress', function(event){
   if event.keycode == Event.KEY_RETURN { 
       //DO STUFF
   }
});

so only watching for keypresses that happen w/in the document

ErsatzRyan
A: 

You can't prevent the event handler from firing. What you can do is check to see where the focus is and only fire when you want it to, e.g. not when the focus is on the address bar.

Kevin
A: 

On Firefox and Chrome (the only two I have to test on at the moment), neither the keydown nor the keypress events fire when the keyboard focus is on the location bar and the Enter key is pressed. When the page loads again, the keyup event fires, because I'm not quick enough releasing it.

So I suppose you could stick with keydown and/or keypress events, or keep track of keydown events and ignore any keyup events that aren't preceded by a keydown.

NickFitz