Skip to content
Merged
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@

We should use two handlers: `document.onkeydown` and `document.onkeyup`.
Ми повинні використовувати два обробники: `document.onkeydown` і `document.onkeyup`.

Let's create a set `pressed = new Set()` to keep currently pressed keys.
Давайте створимо набір `pressed = new Set()`, щоб зберегти поточні натиснуті клавіші.

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.
Перший обробник додає до нього, а другий видаляє. Кожного разу при `keydown` ми перевіряємо, чи достатньо натиснутих клавіш, і запускаємо функцію, якщо це так.
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<html>
<body>

<p>Press "Q" and "W" together (can be in any language).</p>
<p>Натисніть "Q" і "W" разом (можна будь-якою мовою).</p>

<script>
function runOnKeys(func, ...codes) {
Expand All @@ -11,19 +11,19 @@
document.addEventListener('keydown', function(event) {
pressed.add(event.code);

for (let code of codes) { // are all keys in the set?
for (let code of codes) { // чи всі клавіші в наборі?
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 them press all keys again
// під час оповіщення, якщо відвідувач відпускає клавіші,
// JavaScript не отримує подію "keyup"
// і набір натиснутих клавіш продовжуватиме вважати, що клавіша натиснута
// отже, щоб уникнути «липких» клавіш, ми скидаємо статус
// якщо користувач хоче знову запустити гарячу клавішу -- дозвольте йому знову натиснути всі клавіші
pressed.clear();

func();
Expand All @@ -36,7 +36,7 @@
}

runOnKeys(
() => alert("Hello!"),
() => alert("Привіт!"),
"KeyQ",
"KeyW"
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@ 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`.
Створіть функцію `runOnKeys(func, code1, code2, ... code_n)`, яка запускає `func` при одночасному натисканні клавіш із кодами `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)
Наприклад, код нижче показує `alert`, коли `"Q"` та `"W"` натискаються разом (будь-якою мовою, з або без CapsLock)

```js no-beautify
runOnKeys(
() => alert("Hello!"),
() => alert("Привіт!"),
"KeyQ",
"KeyW"
);
Expand Down
Loading