Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger keyboard event in vanilla javascript

Tags:

javascript

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);
like image 744
artemave Avatar asked Sep 30 '14 23:09

artemave


People also ask

How do I use keyboard events in JavaScript?

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.

Can JavaScript simulate key presses?

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.

What JavaScript event when the user pushes a keyboard key?

Events that occur when user presses a key on the keyboard, belongs to the KeyboardEvent Object.


1 Answers

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/

like image 138
Jack Avatar answered Sep 23 '22 19:09

Jack