How to avoid magic numbers when matching event.keyCode in javascript

Can I avoid magic numbers when matching keys in javascript?

The example will use 13 to match the enter key .

I could specify my own constants, but I do not know if these values ​​are sufficient for different platforms / browsers / locales.

+4
source share
1 answer

The first time I tried to do this, I used the charCodeAt method for String. For example, if you want to detect the keystroke "a":

if ("A".charCodeAt(0) == event.keyCode) { /* Do stuff here. */ } 

Note that I used uppercase "A" instead of "a". This is because event.keyCode is only reported as a Unicode value for an uppercase letter (if it is an alpha key). What makes this problem a little hairy is that there are several ways to get the Unicode value for the key that was pressed. In Firefox, you have:

  • event.keyCode
  • event.charCode
  • event.which

According to the Mozilla developer documentation, the Unicode value of the key will be stored in event.keyCode or event.charCode , but not both. No matter which one has the code, it will also be stored in event.which . However, if the value is stored in charCode, it will be case sensitive. Thus, depending on where you get your events from, you may have to check both β€œa” and β€œA”. If you have the luxury of just getting your key event from the onkeydown event, and you focus on Firefox, you can count on getting a case-insensitive code (upper case) set in event.keyCode. In fact, I tested this on Firefox 3.0.3 on Windows XP, Firefox 3.0.4 on MacOS 10.4, Safari 3.2.1 on MacOS 10.4, and OmniWeb 5.8 on MacOS 10.4, and everything works the same. However, I have not tried this in any version of IE, Opera, etc.

If you want to develop it from scratch yourself. I would suggest getting as many different browsers as you can find on different operating systems that you have access to, and experimenting to find out how each browser reports key codes. However, someone has already done this work. It was even mentioned in one of the answers to the question that you linked as your example! This is a jQuery plugin called js-hotkeys . This allows you to register callback functions that will be executed when a key or key combination is pressed. An example of the use that I copied from the project site:

 $(document).bind('keydown', 'Ctrl+a', fn); 

It has been tested to work with various browsers / platforms, so if you are using jQuery this is probably the way to go. If you don't want to use jQuery for some reason, you're out of luck. Apparently, this was based on another script that you could use instead. I have not used any of these libraries personally yet, so I cannot vouch for their ease of use or effectiveness. However, if I had your problem, this is the direction in which I would like to find a solution.

+5
source

All Articles