Luccas
Luccas

Reputation: 4278

How to prevent jquery to keyup when inside textareas?

I have this event binded to my 'body':

$('body').bind('keyup', doSomething);       

But I want to avoid this event inside textareas. Using unbind event when focus on textareas and rebind when blur them costs too much. Is there another way o do that?

Oh, I also tried:

$('body:not(textarea)').bind('keyup', doSomething); 

but didnt work.

Thanks

Upvotes: 0

Views: 533

Answers (3)

nnnnnn
nnnnnn

Reputation: 150080

The two ways that come to mind are:

  1. Within your existing handler test the event.target and do nothing if it is a textarea
  2. Add a second handler on textarea elements that stops propagation of keyup events.

Actual code:

 // option 1
 $('body').bind('keyup', function(e) {
    if (e.target.tagName.toLowerCase()==="textarea")
       return;

    // your existing non-textarea code here
 });

 // option 2
 $('body').bind('keyup', doSomething);

 $('textarea').bind('keyup', function (e) {
    e.stopPropagation();
 });

Demo for option 1: http://jsfiddle.net/XZTaC/

Upvotes: 4

Brian S
Brian S

Reputation: 1061

I've never though to bind to the body for keyup. I would have approached it differently, like so:

$('*').not('textarea').bind('keyup', doSomething);

Upvotes: 0

kinakuta
kinakuta

Reputation: 9037

You could add a separate handler to the textarea that stops propagation of the event:

$('textarea').bind('keyup', function (e) {
  e.stopPropagation();
});

Upvotes: 2

Related Questions