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.
You must use lowercase p in keyPress
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.
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