Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript function to convert keyCodes into characters

Tags:

javascript

Are there any built in functions in any JavaScript framework to convert keyCodes into characters? Which accounts the shift property, so it will return the correct characters.

Or we just have to build our own function ?

like image 1000
strike_noir Avatar asked Apr 08 '26 10:04

strike_noir


1 Answers

You could use String.fromCharCode()

From MDN :

Syntax : String.fromCharCode(num1, ..., numN)

Parameters : num1, ..., numN (A sequence of numbers that are Unicode values.)

This method returns a string and not a String object.

Because fromCharCode is a static method of String, you always use it as String.fromCharCode(), rather than as a method of a String object you created.


Update:

Here I made a function that would do what you want : http://jsbin.com/ukukuq/2/

(Code)

function keyDownEvent(e) {
    var other = {};
    var output= {};
    output['meta'] = {};
    var html = '';

    e = (e) ? e : ((event) ? event : null);

    if (e) {
        output['keyCode']   = (e.keyCode) ? e.keyCode : 'N/A';
        output['charCode'] = (e.charCode) ? e.charCode : 'N/A';
        output['meta']['shift']     =   e.shiftKey  ? true : false;
        output['meta']['ctrl']      =   e.ctrlKey   ? true : false;
        output['meta']['alt']       =   e.altKey    ? true : false;
        output['meta']['meta']      =   e.metaKey   ? true : false;

        html = document.getElementById('output')
        return html.innerHTML += '<pre>keyDown : ' + JSON.stringify(output) + '</pre>';
    } else {
        return 'error';
    }
}

function keyPressEvent(e) {
    var other = {};
    var output= {};
    var html = '';

    e = (e) ? e : ((event) ? event : null);

    if (e) {
        output['keyCode']   = (e.keyCode) ? e.keyCode : 'N/A';
        output['charCode'] = (e.charCode) ? e.charCode : 'N/A';

        html = document.getElementById('output')
        return html.innerHTML += '<pre>keyPress : ' + JSON.stringify(output) + ' Character : <strong>' +  String.fromCharCode(output['charCode']) + '</strong></pre><hr/>';
    } else {
        return 'error';
    }
}

var test = document.getElementById('test');
test.onkeydown = keyDownEvent;
test.onkeypress = keyPressEvent;

like image 66
Pranav 웃 Avatar answered Apr 09 '26 22:04

Pranav 웃



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!