Skip to content

Instantly share code, notes, and snippets.

@kleinschmidt
Created August 15, 2012 16:12
Show Gist options
  • Save kleinschmidt/3361303 to your computer and use it in GitHub Desktop.
Save kleinschmidt/3361303 to your computer and use it in GitHub Desktop.
JS: Collect a one-off keyboard response, using JQuery namespaces to allow multiple, overlapping responses
/* collect a one-off keyboard response, using JQuery namespaces to allow multiple, overlapping responses
* fcn(e): function to be called with event on key press
* keys: vector of allowed keys (as characters, uppercase for alphanumeric) (optional)
* to: timeout for response, in ms (optinal)
* tofcn: function to be called on timeout (optional)
*/
function collect_keyboard_resp(fcn, keys, to, tofcn) {
// create unique namespace for this response
var namespace = '._resp' + (new Date()).getTime();
// bind keyup handler
$(document).bind('keyup' + namespace, function(e) {
// filter key-presses by list of allowed keys, if present
if (!keys || keys.indexOf(String.fromCharCode(e.which)) != -1) {
$(document).unbind(namespace);
fcn(e);
e.stopImmediatePropagation();
return false;
} else {
return true;
}
});
// if timeout function is specified, create event for calling it asynchronously
if (typeof tofcn !== 'undefined') {
$(document).bind('to' + namespace, function() {
$(document).unbind(namespace);
tofcn();
});
}
// if timeout is specified, set all handlers (keyup as well as timeout event) to expire
if (typeof to !== 'undefined') {
// timeout response after specified time and call function if it exists
setTimeout(function(e) {
$(document).trigger('to' + namespace);
$(document).unbind(namespace);
}, to);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment