Question

I am currently developing a web application that requires me to detect if control is pressed.

I use keydown event to set a flag to true if the pressed key is ctrl then keyup event to set that flag to false. I'm using evt.ctrlKey to easily return true if the key pressed is the control key.

But to my surprise, I can see that evt.keyCode is equal to 17 while evt.ctrlKey gives me a false.

This does not happen to keydown event.

Please see this simple fiddle for reproduction. I'm using firefox 27.

PS : I know that I can just test if keyCode is 17 but I want to know if I missed something.

Was it helpful?

Solution

According to w3c docs ctrlKey event attribute returns true if it's presse and false if not, so your code is working right. On keydown event ctrl is pressed - so it returns keycode 17 and true , on keyup ctrl is not pressed, so the result is 17 and false.

OTHER TIPS

The documentation for keyup says:

ctrlKey: true if the control key was down when the event was fired. false otherwise.

The keyup and keydown events are fired after the key has been pressed/released. So the state of ctrlKey is correctly down for the keydown event and up for the keyup event. More explicitly, the order is:

  1. Press CTRL key.
  2. Keydown event is fired.
  3. Release CTRL key.
  4. Keyup event is fired.

Furthermore, if you are looking for the CTRL key itself you should be checking the key code, not the ctrlKey property. The latter is for checking key combinations, for example if you want CTRL+S, you would check for a keyup/keydown event of { keyCode: 83, ctrlKey: true }.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top