Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript catch input when no input has focus

I have bar code scanner.

Sometimes user wants to search items by bar code.

But he is lazy enough and doens't want to use mouse at all to click on input.

Scanner usually inputs from 8 to 13 symbols very fast, no human types so fast.

It would be perfect solution to (1)detect extremely input and if no input element on the page has focus (2) then to select the input with certain class , fill it with content from scanner and start searching.

Second stage is non-issue. I 've no idea how to start with first stage.

Are there any libraries?

Not perfect solution would be to program bar code reader to begin every entering with some key combination and listen for this key and set focus on necessary input. But this would require extra work of other guys.

Is perfect solution reachable?

like image 550
Tebe Avatar asked Dec 18 '22 07:12

Tebe


1 Answers

You could respond to keypress on document by filling in that key in the input and giving it focus, if the target of the keypress isn't an input:

document.addEventListener("keypress", function(e) {
  if (e.target.tagName !== "INPUT") {
    var input = document.querySelector(".my-input");
    input.focus();
    input.value = e.key;
    e.preventDefault();
  }
});
<input type="text" class="my-input">

I was intrigued to find that if I didn't prevent the default, setting the focus made Chrome type the character in the input (but not Firefox). Hence the preventDefault to keep Chrome from doing that.

If you need to support obsolete browsers, you may need to do some playing around with keyCode and/or which rather than using key. MDN claims key support in any modern Chrome or Firefox and IE9+ (doesn't say for Edge).

like image 105
T.J. Crowder Avatar answered Dec 24 '22 02:12

T.J. Crowder