1

I want to take a keystroke and get its ASCII representation. This includes when the SHIFT key is pressed, i.e.

  • "shift =" returns 43
  • "a" returns 97
  • "shift a" returns 65

Is there a way I can do this without writing a lot of code?

Edit:

document.onkeypress = function () {
  console.log(event.which);
}
Josh S.
  • 113
  • 1
  • 2
  • 9
  • Shouldn't it be `function (event) {...`? Otherwise, `event.which` is undefined (or am I wrong?) – flen Mar 14 '18 at 12:00
  • @flen That's correct. Some browsers expose the event as a global window.event, but there are edge cases where it may be the wrong event. Support for window.event is being removed. – Aaron Cicali Sep 12 '19 at 19:10

2 Answers2

4

In very less code, you can do:

document.onkeypress = function () {
  console.log(event.which);
}

Check out your console after running the above code.

ps: The weight of the above code is 55 chars. ;)

Update: It should be onkeypress and not onkeydown. Thanks Timo.

Community
  • 1
  • 1
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
0

Here are the decimal encodings for the upper/lower-case "a" in 7-bit ascii (aka us-ascii).

char    decimal    hexidecimal
A       65         41  
a       97         61

http://www.asciitable.com/

Here's the thing. keyCode != ascii (necessarily). Remember lots of different keyboards, languages, etc. I can select (in software) a us-english layout on a German physical keyboard for instance. That is at an OS level.

Within the browser the form character encoding defaults to the page encoding (e.g. utf-8, iso-8859-1, etc) unless otherwise specified.

You can use the following snippet to take a look at what is in the keypress event.

document.onkeypress = function (e) {
    var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
    console.log('charCode: ' + charCode + 
                ' keyIdentifier: ' + e.keyIdentifier + 
                ' which: ' + e.which + 
                ' keyCode: ' + e.keyCode + 
                ' shiftKey: ' + e.shiftKey + 
                ' ctrlKey: ' + e.ctrlKey + 
                ' altKey: ' + e.altKey + 
                ' metaKey: ' + e.metaKey);
}

The following answer explains that using keypress event is generally the only reliable way to get a character code instead of a key code. And it seems that is what you are after.

JavaScript KeyCode vs CharCode

Sure enough, using onkeypress instead of onkeydown or onkeyup gives me 65 and 97 for "A" and "a". You would need to just update your javascript to ignore events from keys you aren't interested in (ie shift, etc).

Interesting experiment would be to play with page encoding and characters outside the 7-bit ascii range and see how well this method works for getting the actual character encodings.

Community
  • 1
  • 1
mattpr
  • 2,504
  • 19
  • 17