Created
August 15, 2012 16:12
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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