Search code examples
javascriptjquerykeyuponkeyup

preventing javascript keyup function effect when the user is in a text box?


Currently I use the following code to allow the user to "flip through" content on my web app:

$(this).keyup(function(e) {
    if(e.which == 37) {
        document.location = $("#prev_button").attr('href');
    }else if(e.which == 39) {
      document.location = $("#next_button").attr('href');
    }
});

The problem is that if the user is in the search form at the top of the page, I do not want the arrow keys to redirect the page (instead they should act as they normally would without the functionality, i.e. allow the text cursor to move around the text).

the form id is "searchForm" - can I add a clause to the the if statement which evaluates to false if the search form is selected?


Solution

  • I would use something like: Demo

    $(this).keyup(function(e) {
        if(~['input', 'textarea'].indexOf(e.target.tagName.toLowerCase())) return;
        if(e.which == 37) {
            document.location = $("#prev_button").attr('href');
        }else if(e.which == 39) {
            document.location = $("#next_button").attr('href');
        }
    });
    

    This way you can exclude all <input> and <textarea> elements.

    IMO, excluding just #searchbox isn't a great solution because in the future you may change its id or include other text fields, but forget you must reflect changes in the exclusion script.