1

I wrote this simple "webpage" to test out how to check if a key is pressed. It should log 1 if you press the left arrow key and 2 if you press the right arrow key:

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.min.js"></script>

<script>
    window.addEventListener("keydown", function (event) {
        if(event.keyCode == 37 ){
            console.log(1);
        }
        if(event.keyCode == 39 ){
            console.log(2) ;
        }
    });

    $(window).trigger("keydown", { which: 37, keyCode: 37 });
</script>

You can test it. It works fine. However, if I want to trigger this event programmatically through Javascript I fail.

I found this post and tested all methods on it on the window, document and body DOM object and the "script" JQuery objects.

What am I doing wrong?

Community
  • 1
  • 1
J. Doe
  • 13
  • 3
  • How are you trying to trigger that event? – motanelu Feb 19 '17 at 20:24
  • @motanelu I am inserting the code snippets from the post mentioned about into my chrome console and change the which attribute to 37. Already tried to change the attribute to "keyCode" but that neither worked out. – J. Doe Feb 19 '17 at 20:26
  • What do you need it for? Most browsers don't allow triggering keys for security purposes. Check out this answer: http://stackoverflow.com/questions/596481/is-it-possible-to-simulate-key-press-events-programatically/19883789#19883789 – motanelu Feb 19 '17 at 20:46

1 Answers1

0

If you insist on preserving window.addEventListener(), trigger the event without jQuery. See the MDN documentation on this.

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.min.js"></script>

<script>
    window.addEventListener("keydown", function (event) {
        if(event.keyCode == 37 ){
            console.log(1);
        }
        if(event.keyCode == 39 ){
            console.log(2) ;
        }
    });

    var event = new Event("keydown");
    event.keyCode = 37; event.which = 37;
    window.dispatchEvent(event);
</script>
MultiplyByZer0
  • 6,302
  • 3
  • 32
  • 48