Last active
September 22, 2022 10:46
-
-
Save pom421/47062df142b39b25a0181f95b5b49600 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<meta http-equiv="X-UA-Compatible" content="ie=edge"> | |
<title>Document</title> | |
</head> | |
<body> | |
<p>Example to get multiple key pressed</p> | |
<input type="text" placeholder="Type a + p on this input" onkeydown="handleKeydown(event)" onkeyup="handleKeyup(event)"> | |
Résultat : <span id="result">Not found</span> | |
<script> | |
let keysPressed = new Set() | |
function handleKeydown(event) { | |
if (event.key === "Tab") { | |
event.preventDefault() | |
} | |
keysPressed.add(event.key) | |
console.log("handleKeydown", event.key, event.code) | |
let isA, isP | |
isA = isP = false | |
try { | |
keysPressed.forEach(elt => { | |
if (elt === "a") { | |
isA = true | |
} else if (elt === "p") { | |
isP = true | |
} | |
if (isA && isP) { | |
throw ("SUCCESS") | |
} | |
}) | |
} catch (e) { | |
if (e === "SUCCESS") { | |
console.log("A et P trouvées!") | |
document.querySelector("#result").innerHTML = "Found" | |
document.querySelector("#result").style = "background-color: lightblue; padding: 5px" | |
// 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 | |
keysPressed.clear() | |
} | |
} | |
} | |
function handleKeyup(event) { | |
event.preventDefault() | |
console.log("handleKeyup", event.key, event.code) | |
keysPressed.delete(event.key) | |
} | |
function handleClick(event) { | |
console.log("dans click"); | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks you made my day !