keyDown event is not fired for Capslock in Mac

2

CHROME (52):

When turning caps lock ON - only keydown is fired (no event in keyUp or keyPress)

When turning caps lock OFF - only keyup is fired (no event in keyDown or keyPress)

FIREFOX (46):

Only keyDown event is fired for both caps lock ON & OFF (no keyUp or keyPress)

I've read about the keyCodes and events here http://www.quirksmode.org/js/keys.html and in MDN here https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode, aaaand here http://unixpapa.com/js/key.html

But none of the above links talks about this weird behaviour. Is this expected? If so, any easier way to handle it?

Bharath Raja

Posted 2016-08-18T10:49:55.430

Reputation: 179

Answers

3

Yes, this is expected.

Chrome treats the CAPS ON as keydown because it treats the on/off as press and hold, like we hold shift key, which turns on caps on behaviour and turns off when we release it. This Caps Lock button also. When you turn on Caps Lock, chrome handles the 'turn on' as a keypress and when you 'turn off' it handles it as a keyup. But, firefox handles everything as keydown which doesn't make sense to me when compared to how chrome handles the same.

Solution

You should use getModifierState() to get the state of the Caps Lock. This is supported in chrome and firefox.

Hope it helps!

$(function() {
  $(window).on("keydown", function(e){
    if (e.which === 20)
      console.log(e.originalEvent.getModifierState('CapsLock'))
  });
  $(window).on("keyup", function(e) {
    if (e.which === 20)
      console.log(e.originalEvent.getModifierState('CapsLock'))
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Focus here and press 'Caps Lock'

Pranesh Ravi

Posted 2016-08-18T10:49:55.430

Reputation: 9 113