-
Notifications
You must be signed in to change notification settings - Fork 2
/
arbitrary-hotkeys.js
93 lines (79 loc) · 2.58 KB
/
arbitrary-hotkeys.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/**
Arbitrary HotKeys
=================
jQuery plugin that allows you to set arbitrary hotkeys for your HTML page.
Usage:
* Link arbitrary-hotkeys.js in your HTML head:
```
<script type="text/javascript" src="js/arbitrary-hotkeys.js"></script>
```
* Create a div inside head with id="hotkeys" and list the hotkeys you want
in this form:
`<hotkey key="your_hotkey" targetId="id_of_your_html_hyperlink"></hotkey>`
Example:
```
<hotkey key="git" targetId="github"></hotkey>
<hotkey key="goo" targetId="google"></hotkey>
```
* Enjoy!
Copyright (C) 2016 Yuri Dias, Gustavo Moraes
<https://github.com/Yuri-M-Dias>, <https://github.com/gustavosotnas>
reusing code by Christian Brassat and Jukka Svahn:
<https://github.com/crshd/startpage.rwrt/blob/master/js/script.js>
Released under MIT license, see the LICENSE file.
<https://github.com/Yuri-M-Dias/arbitrary-hotkeys>
*/
$(document).ready(function() {
// Detects all hotkeys on the <hotkey> tag
var hotkeys = document.getElementsByTagName('hotkey');
// Declares an array of objects
var strokesMapping = [];
// maps each stroke to an object
for(var key in hotkeys){
// A "key" called 'length' is erroneously recognized by browser here.
// 'length' doesn't have attributes, so this "if" statement avoids to
// throw a TypeError exception and eliminating all other hotkeys
// at assigning "key" and "targetId" object attributes.
if (key === 'length') {
break;
}
// Maps to an object: it's more organized this way, but not needed.
var combination = {
key: hotkeys[key].attributes[0].value,
targetId: hotkeys[key].attributes[1].value
};
// Eliminates undefined ones
if(combination.key === void 0 || combination.key === '' ||
combination.targetId === void 0 || combination.targetId === ''){
continue;
}
// Adds to the avaliable ones
strokesMapping.push(combination);
}
console.log(strokesMapping);
var typed = '';
var typedDate = new Date();
// React on keypress
$(window).keypress(function(e) {
// If we're in an input, we don't want to interpret the keypresses
$('input').keypress(function(e) {
e.stopPropagation();
});
var nowDate = new Date();
var diffMs = (nowDate - typedDate);
if (diffMs > 1000) {
typed = String.fromCharCode(e.which);
} else {
typed = typed + String.fromCharCode(e.which);
}
typedDate = new Date();
strokesMapping.some(function (argument) {
var index = typed.indexOf(argument.key);
if(index >= 0){
console.log($('#' + argument.targetId));
//Clicks the HTML element.
$('#' + argument.targetId)[0].click();
}
});
});
});