0

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?

mgoldwasser
  • 14,558
  • 15
  • 79
  • 103

3 Answers3

3

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();
});
Jason P
  • 26,984
  • 3
  • 31
  • 45
1

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.

Oriol
  • 274,082
  • 63
  • 437
  • 513
  • This solution is 1 line of code, and it prevents all future forms that I may need to add from causing issues. I would advise anyone reading this question to use this solution, as it is generic, concise, and correct. – mgoldwasser Apr 25 '14 at 19:01
1

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;

 }

}
Community
  • 1
  • 1