jrsowles jrsowles - 3 months ago 13
Javascript Question

Focus on HTML element with document-level onkeydown event

When I press the 'p' key, I want a specific text box to come into focus. To do that, I set up an onkeydown listener on the document:

document.onkeydown = function(e) {
// e.preventDefault();
switch (e.key) {
case 'p': {
document.getElementById('test').focus();
break;
}
}
}


When I press 'p', the input does receive focus, but it also types the letter 'p' into the input, which I don't want. I just want focus on the empty text box. When I tried adding e.preventDefault to the listener, that stopped the 'p' from showing up, but it also prevented me from typing anything into the text box at all.

How can I focus on the text box without it typing in the shortcut key? If at all possible, I'd like to accomplish this in pure JavaScript.

Here's the JSFiddle: https://jsfiddle.net/qau6woL6/

Answer

Add return false after focusing the field:

document.onkeydown = function(e) {
  switch (e.key) {
    case 'p':
      {
        document.getElementById('test').focus();
        return false;
      }
  }
};
<input id="test" />