JSFiddle - React, Tailwind, and code Playground

by surfine

HTML

<p>Press a key anywhere to see the value is updated on keydown as well as onkeypress:</p>
Key Down: <input type="text" id="keyDown" readonly /><br/>
Key Pressed: <input type="text" id="keyPress" readonly />

CSS

input { width: 50px; }

JavaScript

$(function() {
    var $kp = $('#keyPress');
    var $kd = $('#keyDown');
    var $ku = $('#keyUp');

    var _to_ascii = {
        '188': '44',
        '109': '45',
        '190': '46',
        '191': '47',
        '192': '96',
        '220': '92',
        '222': '39',
        '221': '93',
        '219': '91',
        '173': '45',
        '187': '61', //IE Key codes
        '186': '59', //IE Key codes
        '189': '45'  //IE Key codes
    }

    var shiftUps = {
        "96": "~",
        "49": "!",
        "50": "@",
        "51": "#",
        "52": "$",
        "53": "%",
        "54": "^",
        "55": "&",
        "56": "*",
        "57": "(",
        "48": ")",
        "45": "_",
        "61": "+",
        "91": "{",
        "93": "}",
        "92": "|",
        "59": ":",
        "39": "\"",
        "44": "<",
        "46": ">",
        "47": "?"
    };

    $(document).on('keydown', function(e) {
        var c = e.which;

        if (_to_ascii.hasOwnProperty(c)) {
            c = _to_ascii[c];
        }
        
        if (!e.shiftKey && (c >= 65 && c <= 90)) {
            c = String.fromCharCode(c + 32);
        } else if (e.shiftKey && shiftUps.hasOwnProperty(c)) {
            c = shiftUps[c];
        } else {
            c = String.fromCharCode(c);
        }

        $kd.val(c);
    }).on('keypress', function(e) {
        $kp.val(String.fromCharCode(e.which));
    });



});