Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.