en.javascript.info/2-ui/3-event-details/5-keyboard-events/2-check-sync-keydown/solution.view/index.html
2018-08-02 15:15:35 +01:00

47 lines
1 KiB
HTML

<!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 them press all keys again
pressed.clear();
func();
});
document.addEventListener('keyup', function(event) {
pressed.delete(event.code);
});
}
runOnKeys(
() => alert("Hello!"),
"KeyQ",
"KeyW"
);
</script>
</body>
</html>