views:

541

answers:

3

I've defined some global keyboard handling using jQuery's keypress event.

Is there a way to suppress these events for input/textarea fields so as not to interfere with typing?
I've used some hacks with conditions based on element selectors, but those had a big performance impact as they were fired on every single keypress.

(Some of those fields are created dynamically, which is beyond my control - perhaps that's relevant.)

+3  A: 

Create an onfocus handler for all input and textareas that sets some global variable indicating that keyboard events should be ignored. Create another handler for the blur event to reset the global variable.

var DISABLE_KEY_HANDLERS = false;

$('input[type=text], input[type=password], textarea').focus(function(){
  DISABLE_KEY_HANDLERS = true
})

$('input[type=text], input[type=password], textarea').blur(function(){
  DISABLE_KEY_HANDLERS = false
})

In your key handlers you would just have to check if the value is true or not, and return if it is true.

Zach
Thanks!The problem, though, are the dynamically-created elements; I'd have to re-run the above code whenever a new input field is created, which is beyond my control.Nevertheless, this does help, and maybe I can find a workaround for dynamic parts...
You should look into the livequery plugin: http://plugins.jquery.com/project/livequery/
Zach
That looks promising - many thanks!
jQuery 1.3+ has a live() function built in, you should check this out as well if you are using 1.3+ http://docs.jquery.com/Events/live
Jon Erickson
live() doesn't support focus yet.
Zach
+1  A: 

Turns out the event already provides me with everything I need; ev.target is the active DOM element, so I can check whether that's an input field.

A: 

Would help if you shared your answer in code as well :)

Heilemann