-
Notifications
You must be signed in to change notification settings - Fork 0
/
keysequence.js
45 lines (37 loc) · 1.07 KB
/
keysequence.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
* invokes fn when passed key sequence is typed within passed threshold.
*
* @param {string} sequence of characters such as `qwerty`.
* @param {number} threshold between key presses in milliseconds.
* @param {function} function to be invoked when sequence is typed successfully.
* @return {object} object containing method to remove eventlistener.
*/
function keySequence(keySequence, threshold, fn) {
'use strict'
var keyspressed = [];
var deadline = null;
var reset = function() {
keyspressed = [];
}
var onPress = function(e) {
if (deadline) {
clearTimeout(deadline);
}
deadline = setTimeout(reset, threshold);
if (keyspressed.length === keySequence.length) {
reset();
}
var keyCode = e.keyCode || e.charCode;
var character = String.fromCharCode(keyCode);
keyspressed.push(character);
if (keyspressed.join('') === keySequence) {
fn();
}
}
document.addEventListener('keypress', onPress, false);
return {
remove: function() {
document.removeEventListener('keypress', onPress);
}
}
}