Michael T
Michael T

Reputation: 45

javascript keydown shortcut function but ignore if in text box

I have set a one key skip/change page function. but when user want to type "0" in input text or text area, the one key function also effect and change to another page.

How can i ignore this java script when user using text input or text area?

document.onkeydown=nextpage; 
function nextpage(){
  var event=document.all?window.event:arguments[0]; 
  if (event.keyCode==13) location="#skipcontent"; 
  if (event.keyCode==48) location="contact-us.php";
} 

Upvotes: 4

Views: 2095

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074829

Examine the target element to see what element the event was targeting:

document.onkeydown=nextpage; 
function nextpage(e){
  var event = document.all ? window.event : e;
  switch (e.target.tagName.toLowerCase()) {
    case "input":
    case "textarea":
    case "select":
    case "button":
    // ...and so on for other elements you want to exclude;
    // list of current elements here: http://www.w3.org/TR/html5/index.html#elements-1
      break;
    default:
      if (event.keyCode==13) location="#skipcontent"; 
      if (event.keyCode==48) location="contact-us.php";
      break;
  }
}

Or instead of a switch, you could use a regular expression with an alternation:

document.onkeydown=nextpage; 
function nextpage(e){
  var event = document.all ? window.event : e;
  if (!/^(?:input|textarea|select|button)$/i.test(e.target.tagName)) {
    if (event.keyCode==13) location="#skipcontent"; 
    if (event.keyCode==48) location="contact-us.php";
  }
}

Side note: You might look at using addEventListener, which is supported on all modern browsers and allows for multiple handlers per event per element. If you have to support IE8, this answer has a function you can use which falls back to attachEvent and handles the event object shuffle for you.

Upvotes: 6

Related Questions