How to get the key pressed?

8

I'm breaking my head to create a function that returns the code of the key pressed. I found this:

function inicializa(){
    document.addEventListener('keydown', pegaTecla);
}

function pegaTecla(){
  var tecla = event.keyCode;
  alert(tecla);
}

But with this function I only get the key code to appear via alert and if I try return on the pegaTecla() function it does not return and it is not called every time I press any key.

How do I do when I press a key to return the key to me later?

Here is the code in its entirety . And here the end result .

It works by displaying the key code every time I press a key.

    
asked by anonymous 16.02.2015 / 04:58

3 answers

7

You only need to use String.fromCharCode() to get the key pressed (instead of the number).

var pressed = document.getElementById('pressed');

function keyPressed(evt){
    evt = evt || window.event;
    var key = evt.keyCode || evt.which;
    return String.fromCharCode(key); 
}

document.onkeypress = function(evt) {
    var str = keyPressed(evt);
    pressed.innerHTML += str;
};
<h2 id='pressed'>Teclas pressionadas: </h2>

Example requested in comments:

function keyPressed(evt){
    evt = evt || window.event;
    var key = evt.keyCode || evt.which;
    return String.fromCharCode(key); 
}

document.onkeypress = function(evt) {
    var str = keyPressed(evt);
    
    if(str == 'f')
        alert("Apertou o 'f', chamando uma função...");
};
<p>Pressione a tecla F</p>
    
16.02.2015 / 05:20
4

One of the possible reasons is that using% direct% as you did is equivalent to event , but this event is not accessible by all browsers. You should use the first parameter of the function that is added to the callback of window.event , like this:

'.addEventListener(..., function(event){ ... })'

Another reason is that you only used addEventListener , in order to get the code you should also use (in addition to .keyCode ) .keyCode .

An example:

var el = document.getElementById("result");

function minhaFuncao(codigo) {
    el.innerHTML += ", " + codigo;
}

document.addEventListener('keydown', function(e) {
    e = e || window.event;
    var code = e.which || e.keyCode;

    minhaFuncao(code);
});
<div id="result">Teclas:</div>
    
16.02.2015 / 05:10
-1

I saw that your question has already been resolved, but it costs nothing to leave here a small plugin with only the desired one, to know which button code was pressed

link

<script src='jquery.js'></script>
<input class='keydown' placeholder='keymap' autofocus />
<script>
    $('input.keydown').on('keydown', function(e) {
        event.preventDefault();
        $('input.keydown').val(e.keyCode); });
</script>
    
27.05.2017 / 13:02