Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addEventListener keyPress doesn't register key presses [closed]

Tags:

javascript

I want to call a function when a key is pressed. I've found the window.addEventListener(type, handler) function to do this when type = "keyPress"; however, that doesn't seem to call the handler when keys are pressed.

Here's the code that I'm using:

window.addEventListener("keyPress", myEventHandler);

function myEventHandler(event){
    console.log(event);
}

After focusing on the browser window, I expect key presses to be logged in the console; however, pressing keys doesn't produce any output.

like image 536
Zim Avatar asked Jun 04 '14 02:06

Zim


2 Answers

You must use lowercase p in keyPress

like image 152
John Avatar answered Oct 18 '22 09:10

John


The event name must be keypress - small p

window.addEventListener("keypress", myEventHandler, false);

Demo: Fiddle

Apart form that since you are using jQuery use a jQuery solution like

//no need to use dom ready since the event is added to window
$(window).keypress(function (e) {
    //use e.which
    var keyCode = e.which;
    console.log(e, keyCode, e.which)
    if (keyCode == 88) {
        console.log("You pressed W!");
        //alert("You pressed W!");
    }
})

Demo: Fiddle

event.which

The event.which property normalizes event.keyCode and event.charCode. It is recommended to watch event.which for keyboard key input. For more detail, read about event.charCode on the MDC.

like image 28
Arun P Johny Avatar answered Oct 18 '22 08:10

Arun P Johny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!