Last active
April 30, 2022 00:31
-
-
Save whoisryosuke/ca52cf287078eb72aee81bf2c0344e0c to your computer and use it in GitHub Desktop.
JS - Simulate keyboard events declaratively using the KeyboardEvent API - @see: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent -- @example: https://stackoverflow.com/a/11885974 --- DOES NOT WORK WITH TAB!: https://stackoverflow.com/questions/1601593/fire-tab-keypress-event-in-javascript
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
<div id="output" style="background:green;min-height:40px"> | |
</div> |
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
var output = document.getElementById("output"); | |
output.prepend("'KeyboardEvent' constructor status: " + (/\[native\s+code\]/i.test(KeyboardEvent + "") ? "NATIVE" : "POLYFILL")) | |
document.addEventListener("keydown", function(e) { | |
output.insertAdjacentHTML("afterbegin", | |
"<b>char: </b>" + e.char + " | " + | |
"<b>key:</b> " + e.key + " | " + | |
"<b>shiftKey:</b> " + e.shiftKey + " | " + | |
"<b>keyCode:</b> " + e.keyCode + " | " + | |
"<b>location:</b> " + e.location + "<br/>") ; | |
e.preventDefault(); | |
}); | |
function simulateKeyEvent(character) { | |
var keyEvent = new KeyboardEvent("keydown", {key : character, char : character, shiftKey: true}); | |
document.dispatchEvent(keyEvent); | |
console.log('run event') | |
} | |
simulateKeyEvent('a'); | |
simulateKeyEvent('b'); | |
simulateKeyEvent('c'); | |
// You should see c, b, and a in the list in that order |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment