jquery: do this on keyup, unless the person is in a textarea or input
Asked Answered
R

3

6

my script works but i don't understand how to make it NOT launch the functions when in a textarea/input and those keys are pressed. aka: launch the event when the user presses that key, unless the user is in a textarea/input.

$('body').keyup(function (event) {

var direction = null;
if (event.keyCode == 37) {
  $('#wrapper').fadeOut(500)
} else if (event.keyCode == 39) {
        $('html,body').animate({scrollTop: $('body').offset().top}, {duration: 1500, easing: 'easeInOutQuart'}
        )
return false;    
}
     })
Recognizance answered 24/9, 2010 at 14:16 Comment(0)
S
10

Just check event.target:

$('body').keyup(function(event) {
    if ($(event.target).is(':not(input, textarea)')) {
       ...
    }
});

In this case you will still have only one event handler (attached to the body) but it will filter for elements that recieves the event

Stymie answered 24/9, 2010 at 14:24 Comment(2)
Why assign the event to the input in the first place if you never want to handle it?Onitaonlooker
Here we assign event to the body, not to the input. And later just filter with input and textarea.. It's much better then assign event to all elements except inputsStymie
M
1

Try:

$('body *:not(textarea,input)').keyup(function (event) {

});
Mousterian answered 24/9, 2010 at 14:21 Comment(2)
Such selection is incorrect since it will add as much event handlers as much elements you have on the page.Stymie
almost right (textareas are not included), but this will workMousterian
B
1
$('body :not(textarea,input[type=text])').keyup(function (event) {

or

$('body').not('textarea,input[type=text]').keyup(function (event) {
Backspin answered 24/9, 2010 at 14:23 Comment(4)
This one has same problem as Thariama's solutionStymie
Just imagine that page has 10000 elements (not too much). Will you assign event to each element? It does not makes senseStymie
I suppose it's a good design decision for the OP. however, not what he was asking about.Backspin
I'm just suggesting to think about performance of your solution. Whatever he asked for.Stymie

© 2022 - 2024 — McMap. All rights reserved.