Gaurang Tandon
Gaurang Tandon

Reputation: 6753

A simple e.altKey test

Summary:

I want to catch the event of Alt + Z onkeypress. I am using e.altKey to accomplish this. However, it isn't working anywhere, from textareas to inputs to div[contenteditable]s!


FIDDLE

The event of Shift + any_key (any_key !== Alt) works fine, but Alt isn't detected at all. I tested with keydown, which works perfectly.


I don't know if it is related, but the ctrl key also doesn't work in my fiddle. I have seen ctrl key being caught onkeypress in various answers like this one: https://stackoverflow.com/a/4604093/2675672 , but I have zero idea why it doesn't work in my fiddle.

By not working, I mean that, even no alert boxes pop up.

It must be something simple which I might be overlooking.


Note: Only Chrome support required, without any libraries. Also, my Alt key isn't broken. I can press Alt + F and open the File menu in Chrome just fine.

EDIT:

So, it is realized that this is a Chrome bug that the event doesn't fire (noticed by @Pointy). Still, if anyone has any workarounds for making this work. Please share them. Thanks!


UPDATE: it's been 3 years. Is it ok for Chromium bugs to take years to fix? Or should I just forget it (I'd forgotten this question already, just came across it while maintenance work)

Upvotes: 0

Views: 340

Answers (1)

Dávid Szabó
Dávid Szabó

Reputation: 2247

Onkeypress doesn't fire for all keys.

You need to use onkeydown.

Note: The onkeypress event is not fired for all keys (e.g. ALT, CTRL, SHIFT, ESC) in all browsers. To detect only whether the user has pressed a key, use the onkeydown event instead, because it works for all keys.

Quote from: http://www.w3schools.com/jsref/event_onkeypress.asp

Upvotes: 1

Related Questions