I am trying to follow currently recommended way of triggering dom events (using event constructors that is) and it does not work for me (in Chrome)
This is my code (http://jsfiddle.net/artemave/shg7ot58/):
document.addEventListener(function(e) {
alert("hallo");
});
var e = new KeyboardEvent("keydown", {
key: "Escape", // keyCode: 27 also does not work
bubbles: true,
cancelable: true
});
document.dispatchEvent(e);
There are three different keyboard events in JavaScript: keydown : Keydown happens when the key is pressed down, and auto repeats if the key is pressed down for long. keypress : This event is fired when an alphabetic, numeric, or punctuation key is pressed down. keyup : Keyup happens when the key is released.
If you need keyup events too, it is also possible to simulate keyup events by changing "keydown" to "keyup" in the code snippet. This also sends the event to the entire webpage, hence the document . If you want only a specific element to receive the event, you can substitute document for the desired element.
Events that occur when user presses a key on the keyboard, belongs to the KeyboardEvent Object.
Add event type, keydown
to the addEventListener
method to listen for your custom dispatched event.
document.addEventListener('keydown', function(e) {
alert("hallo");
});
Fiddle: http://jsfiddle.net/shg7ot58/1/
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