Search code examples
javascriptcharacter-encodingcharturkishfromcharcode

javascript convert to turkish character fromCharCode


I print the value entered from the keyboard to the screen. but Turkish characters are written to the screen in a distorted way. How can I print Turkish characters properly?

my javascript codes:

window.addEventListener('keyup',function(event){

    var span = this.document.createElement('span');
    span.innerText= String.fromCharCode(event.keyCode);
    span.style.color='white';
    var harfDivleri = this.document.querySelectorAll('.harfDivleri');

    var i = kelimeDiv.children.length;
    while (0 < i) {
        i--;
         if(harfDivleri[i].innerHTML == ""){
            harfDivleri[i].appendChild(span);
        }
    }
    
});

screen output:

enter image description here

I want to be able to write such characters: ÖÜĞİŞÇ


Solution

  • I'd suggest using the keypress event, this will give you the actual character code as opposed to the physical key clicked, this is explained in more detail here

    The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered. For example, a lowercase "a" will be reported as 65 by keydown and keyup, but as 97 by keypress. An uppercase "A" is reported as 65 by all events.

    If you use the keypress event, your code should work as expected, see the simple demo below, Turkish characters should be rendered correctly.

    window.addEventListener('keypress', function(event){
        document.getElementById('output').innerHTML += String.fromCharCode(event.keyCode);
    })
    <h3>Type here to see text:</h3><br>
    
    <h3 id='output'></h3>