1
<body>
  <div>Sample div</div>
  <input type='text'/>
</body>

$(document).delegate('body *:not(input)', 'keyup', function(e){
    if((e.keyCode || e.which) == 39){ //right arrow
        $('#next_image').click();
    }
    if((e.keyCode || e.which) == 37){ //left arrow
        $('#prev_image').click();
    }
}

I'm using jQuery Cycle library to setup slideshow. It's more like a photo album, where you can use keyboard shortcuts to do some stuff. So, the slideshow is the whole page, which also contains input fields. Hence, when you are writing a text inside of input field and try to move cursor with keyboard (left and right arrow buttons), it would fire the event and scroll to the next/prev image.

Any ideas on how to enable keyup events on everything BUT the input field? Obviously, current selector doesn't work.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Sherzod
  • 5,041
  • 10
  • 47
  • 66

1 Answers1

3

If you want to stick with .delegate() instead of the currently-favored .on():

$(document).delegate(':not(input)', 'keyup', function (e)
{
    if (e.which === 39) $('#next_image').click();
    else if (e.which === 37) $('#prev_image').click();
});
  • jQuery normalizes key code information, so you only need to check event.which
  • If you did have to check keyCode and which, (e.keyCode || e.which) == 39 would not work properly, since || will evaluate to the first truthy operand, or the second operand if both are falsy. To put it differently: you'd have to check each one separately, like this:

    if (e.which === 39 || e.keyCode === 39)
    
  • It's generally better to use === instead of ==. See Which equals operator (== vs ===) should be used in JavaScript comparisons?

doesn't work... it's still firing the keyup event inside of <input>

Ah yes. I'm thinking it's because of event bubbling.

I've seen it solved using an extra event handler (imgur caption boxes in the gallery):

$('input').live('keyup', function (e) {
    if(!e.ctrlKey && !e.altKey && !e.metaKey) {
        if(e.keyCode==37 || e.keyCode==39 || e.keyCode==13) {
            e.stopPropagation();
        }
    }
    return true;
});

http://jsfiddle.net/mattball/DQusL/

Community
  • 1
  • 1
Matt Ball
  • 354,903
  • 100
  • 647
  • 710