0

I'm trying to alert any key-pressed :

alert(String.fromCharCode(e.which));

Seems to work for A-Z a-z characters but not for any other characters.

My goal is to make it work for any character (WYSIWYG).

isherwood
  • 58,414
  • 16
  • 114
  • 157
Hezi-Gangina
  • 637
  • 6
  • 20
  • You haven't shown how you're hooking this up to an event... – Jon Skeet May 19 '15 at 14:41
  • document.body.onkeyup=function(e) – Hezi-Gangina May 19 '15 at 14:42
  • That should be part of the question then - ideally as part of a complete script containing everything required to demonstrate the problem. – Jon Skeet May 19 '15 at 14:42
  • What do you expect to be output when you press `enter`? When you press `Ctrl+alt+F8`? When you press `画`? – Camusensei May 19 '15 at 14:43
  • ! = ! (and not 1) @ = @ (and not 2) etc... – Hezi-Gangina May 19 '15 at 14:43
  • I can deal with enter/esc/tab/backspace later... This is not the case here... – Hezi-Gangina May 19 '15 at 14:44
  • The `keydown` and `keyup` events tell you about the key code - the identifier for the keyboard button that was pressed. The event should also tell you the state of the modifier keys, but you'll have to guess what those mean - different keyboard layouts have different shifted special characters. – Pointy May 19 '15 at 14:50
  • 1
    "When you catch a keyboard event, you may wish to know which key was pressed. If so, you may be asking too much. This is a very big mess of browser incompatibilities and bugs" If you wish to continue there, have a look at "3. Identifying Keys" in http://unixpapa.com/js/key.html – Camusensei May 19 '15 at 14:55

1 Answers1

1

You can manually provide your own mappings, see my jsfiddle example: https://jsfiddle.net/Glogo/dab3hzz7/1/

sample code:

function myStringFromCharCode(which) {
    var strKey = String.fromCharCode(which);

    switch(which) {
        case 13: return "Shift"
        case 17: return "Ctrl"
        case 18: return "Alt"
        // add more mappings here ...
    }

    return strKey;    
}

function myOnKeyUp(e) {
    alert(e.which + "=" + myStringFromCharCode(e.which));
}

document.body.onkeyup=myOnKeyUp;
Glogo
  • 2,694
  • 2
  • 23
  • 23
  • Thanks man! I was wondering if it would be possible to get the real characters values of ! @ # $ % ^ & * ( ) – Hezi-Gangina May 21 '15 at 08:57
  • For these character you will probably need to be able to catch multiple keys (depending on your keyboard layout, for example on english keyboard @ is Shift+2). See this question: http://stackoverflow.com/questions/5203407/javascript-multiple-keys-pressed-at-once But I'm not sure how to get the outputted character since it depends on keyboard layout – Glogo May 21 '15 at 09:04