Question

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?

Was it helpful?

Solution 2

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.

OTHER TIPS

You can stop the propagation of the event when in the textbox so the event doesn't make it to your other handler:

$('#searchbox').keyup(function(e) {
    e.stopPropagation();
});

Check out this thread :) Find if a textbox is currently selected

function checkFocus() {

  if ($(document.activeElement).attr("type") == "text" || $(document.activeElement).attr("type") == "textarea") {

  //Something's selected

  return true;

 }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top