I am looking for a way to simulate a keyboard press (like the titled suggests). I have looked around and I have found mainly these 2 SO questions:
The issue with those are that they both use the KeyboardEvent.initKeyboardEvent()
event which according to MDN it is deprecated. Is there a different way of accomplishing the same thing without that deprecated function?
I would like to know this because I am creating a script for YouTube using Chrome's TamperMonkey extension. This script will, when [space] is pressed, trigger K. K is YouTube's toggle play/pause button. I have the [space] listener working perfectly with the code below:
document.addEventListener("keydown", function(e) {
if(e.keyCode==32) {
e.preventDefault();
}
}, false);
Also I am really looking for a pure JavaScript approach.
If you do this with jQuery you build your event.
https://stackoverflow.com/a/3368599/3257830
If you want to create an event, you initialize the object then dispatch the event.
https://developer.mozilla.org/en-US/docs/Web/API/Event/Event
document.addEventListener("keypress", function(e) {
alert(e.which);
});
var e = new Event("keypress");
e.which = 65;
e.keyCode = 65;
document.dispatchEvent(e);
<p id="r">Alerts on event</p>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With