Athanatos Athanatos - 4 months ago 28x
jQuery Question

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.

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



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) {

    // 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.