Reputation: 93993
I'm building a site that after the page is loaded, needs to listen for a particular keyboard string.
The event I am interested in is actually a scanner scanning an object, but it presents to the site as keyboard input, of the form ~XXX~
.
I see jQuery has a keypress()
event that you can bind to a particular object.
But how can I listen for general keyboard input, after $(document).ready
?
Upvotes: 13
Views: 16404
Reputation: 163318
Try this:
$(function() {
$(window).keypress(function(e) {
var key = e.which;
//do stuff with "key" here...
});
});
See it in action on jsFiddle
Upvotes: 19
Reputation: 92334
I've done this before. There are many other things to worry about besides how to handle keypress events.
Your scanner probably sends the input wrapped by a start and end characters. I would create a ScanReader object that attaches to the keypress event. Once it detects the start character, it starts accumulating the presses until the end character is detected.
To prevent it from getting confused with the user typing, the keypresses should be relatively close (in time) to each other, you need to test it out and see what a good number of ms between keypresses is. Fast typers can type as fast as 50ms in between key presses.
Upvotes: 1