0

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)

Community
  • 1
  • 1
Gaurang Tandon
  • 6,504
  • 11
  • 47
  • 84
  • It works fine if you assign the event handler properly http://jsfiddle.net/CPsRe/ *edit* wait no that's wrong; it works no matter what in Firefox. It's Chrome that's the problem here. See this for example: https://code.google.com/p/chromium/issues/detail?id=2606 – Pointy Jun 23 '14 at 14:47
  • @Pointy Thanks for the reply, but it still doesn't work :( – Gaurang Tandon Jun 23 '14 at 14:48
  • Yes I realized that I was mistaken. Chrome just has bad behavior with keyboard events (and probably Safari too; it seems to be a WebKit issue). – Pointy Jun 23 '14 at 14:51

1 Answers1

1

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

Dávid Szabó
  • 2,235
  • 2
  • 14
  • 26
  • What if I press `Alt + Z`? That way, `Z` is being pressed and so the event should fire I believe. Also, then why does `Shift` key work when it's written it should not? ("all keys (e.g. ALT, CTRL, SHIFT, ESC) "? – Gaurang Tandon Jun 23 '14 at 14:51
  • 1
    Stop using keypress at all. Do everything with keydown. Those were just examples, but i have no idea why that works. Probably in IE or other browsers it is not working. – Dávid Szabó Jun 23 '14 at 14:53