Skip to content

Instantly share code, notes, and snippets.

@you-think-you-are-special
Created March 30, 2015 08:42
Show Gist options
  • Save you-think-you-are-special/d7ea1259033d67fb7f97 to your computer and use it in GitHub Desktop.
Save you-think-you-are-special/d7ea1259033d67fb7f97 to your computer and use it in GitHub Desktop.
JavaScript barcode scanner detector
function BarcodeScannerDetector(options) {
this.options = options || {}; // Default
this.options.keypressDelay = this.options.keypressDelay || 100; // Delay between press
this.chars = []; // Our barcode
this.events();
}
BarcodeScannerDetector.prototype.delay = function(callback, ms) {
clearTimeout(this.timer);
this.timer = setTimeout(callback, ms);
};
BarcodeScannerDetector.prototype.events = function() {
var _this = this;
window.onkeypress = function(e) {
if (e.which >= 48 && e.which <= 57) {
_this.chars.push(String.fromCharCode(e.which));
_this.delay(function() {
if (_this.chars.length >= 10) {
console.log("Barcode scanned: " + _this.chars.join(""));
}
_this.chars = [];
}, _this.options.keypressDelay);
}
};
};
new BarcodeScannerDetector(); // init
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment