Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery keypress event ignore arrow keys

I have an input box that acts like a search (similar to facebook). I am using the jquery on key-press event which works fine. The problem is that I can't scroll down on the set of the results using the arrow keys, every time that one of them is pressed the search results are being regenerated. So is it possible to ignore the arrow keys / shift / tab etc.

http://jsfiddle.net/UU6KG/

$("#search-form .search-terms").on("keypress", function(){
       $("#search-items #autocom").fadeIn();
    });

Thanks

like image 605
Athanatos Avatar asked Jul 23 '13 10:07

Athanatos


1 Answers

You need to filter out the arrow key codes (37,38,39,40), try this:

Note the function(e) in place of function() - this allows you to grab the event and therefore the key code.

$('#search-form .search-terms').on('keydown', function(e){
    // get keycode of current keypress event
    var code = (e.keyCode || e.which);

    // do nothing if it's an arrow key
    if(code == 37 || code == 38 || code == 39 || code == 40) {
        return;
    }

    // do normal behaviour for any other key
    $('#search-items #autocom').fadeIn();
});

Click for a list of key codes

A note from the docs on keypress/keyup/keydown:

Note that keydown and keyup provide a code indicating which key is pressed, while keypress indicates which character was entered. For example, a lowercase "a" will be reported as 65 by keydown and keyup, but as 97 by keypress. An uppercase "A" is reported as 65 by all events. Because of this distinction, when catching special keystrokes such as arrow keys, .keydown() or .keyup() is a better choice.

The keypress event works in almost all situations but it's prudent to use keyup or keydown because some browsers (I think some older version of Firefox) don't detect certain keys, such as arrow keys, using the keypress event.

like image 93
theyetiman Avatar answered Oct 01 '22 05:10

theyetiman