How to get the key pressed?

Asked

Viewed 19,850 times

12

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

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

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

But with this function I can only get key code to be displayed via alert and if I try return in function pegaTecla() does not return and is not called every time q press some key.

How do I stop when I press a key the function returns me that key for later it is tested?

Here’s the code in full.
And here the final result.

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

4 answers

10


All you had to do was 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 the 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>

  • Ah, now that I saw that I needed the code (and not the letter). Anyway, here is the example :)

  • and how do I execute a function so q pressed a key ? pq qro create a routine in which a key is displayed on the screen and the user has to press it. to make the function perform a comparator with difficulty so that the user presses the -key

  • @Leandromacedo added an example.

  • 1

    Thank you very much I managed to do what you need :)

6

One of the possible reasons is that the use of event direct as you did is equivalent to window.event, however this event is not accessible by all browsers. You must use the first parameter of the function that is added to the callback of the addEventListener, thus:

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

Another reason is that you just used .keyCode, to be able to catch the code you must also use (in addition to the .keyCode) the .which.

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>

  • cool, I didn’t know it thanks.

  • and how to perform a function so q pressed a key ?

  • pq Create a routine where a key is displayed on the screen and the user has to press it. to with difficulty to make the function perform a comparator so the user press the key

  • @Leandromacedo I edited the answer, click on "Run code snippet" and test please see how the code looked, this is it?

  • Thank you very much @guilhermenascimento vc tb helped me a lot

  • @Leandromacedo It is that really I had not understood what you wanted, I just understood where the problem was, but how good it worked.

  • yeah, it worked out.

  • but now toh with another problem kkk. qro clear the screen every time q will draw a letter. here’s how it is and the problem :/ https://jsfiddle.net/leandroMacedo/d806crks/

  • hahaaha ihull got used context.clearRect(); Agr’s the way q qria

Show 4 more comments

-1

to pick up the letter itself is used

iputs[x]. addeventlistener("keypress", Function() { console.log(Event.key) // if I click 'p' it will return me 'p' unlike the keycode that returns the key code

})

-1

I see your doubt has been resolved, but it costs nothing to leave a little plugin with just the desired, know which button code was pressed

http://dkteclive.com/plugins/keymap.html

<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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.