This commit is contained in:
Ilya Kantor 2017-03-12 12:54:13 +03:00
parent fc84391bd2
commit 8360ebbe90
60 changed files with 920 additions and 1672 deletions

View file

@ -0,0 +1,6 @@
We should use two handlers: `document.onkeydown` and `document.onkeyup`.
The set `pressed` should keep currently pressed keys.
The first handler adds to it, while the second one removes from it. Every time on `keydown` we check if we have enough keys pressed, and run the function if it is so.

View file

@ -0,0 +1,47 @@
<!DOCTYPE HTML>
<html>
<body>
<p>Press "Q" and "W" together (can be in any language).</p>
<script>
function runOnKeys(func, ...codes) {
let pressed = new Set();
document.addEventListener('keydown', function(event) {
pressed.add(event.code);
for (let code of codes) { // are all keys in the set?
if (!pressed.has(code)) {
return;
}
}
// yes, they are
// during the alert, if the visitor releases the keys,
// JavaScript does not get the "keyup" event
// and pressed set will keep assuming that the key is pressed
// so, to evade "sticky" keys, we reset the status
// if the user wants to run the hotkey again - let him press all keys again
pressed.clear();
func();
});
document.addEventListener('keyup', function(event) {
pressed.delete(event.code);
});
}
runOnKeys(
() => alert("Hello!"),
"KeyQ",
"KeyW"
);
</script>
</body>
</html>

View file

@ -0,0 +1,19 @@
importance: 5
---
# Extended hotkeys
Create a function `runOnKeys(func, code1, code2, ... code_n)` that runs `func` on simultaneous pressing of keys with codes `code1`, `code2`, ..., `code_n`.
For instance, the code below shows `alert` when `"Q"` and `"W"` are pressed together (in any language, with or without CapsLock)
```js no-beautify
runOnKeys(
() => alert("Hello!"),
"KeyQ",
"KeyW"
);
```
[demo src="solution"]