javascript – How to know which key was pressed

Question:

I need that every time a key is pressed, a function is executed, which will vary depending on the key that was pressed. So I need to know which key was pressed.

This is what I have so far:

function onKeyDownHandler() {
     console.log("key pressed ",  String.fromCharCode(event.keyCode));
}
<input onkeydown="onKeyDownHandler();"/>

But I still can't get the value of the pressed key.

Answer:

You could do something like the following:

function onKeyDownHandler(event) {

    var codigo = event.which || event.keyCode;

    console.log("Presionada: " + codigo);
     
    if(codigo === 13){
      console.log("Tecla ENTER");
    }

    if(codigo >= 65 && codigo <= 90){
      console.log(String.fromCharCode(codigo));
    }

     
}
<input onkeydown="onKeyDownHandler(event);"/>

The first thing we do is include the event variable in the OnKeyDown event. This serves so that when the event is executed, it can have access to the information relating to the key.

<input onkeydown="onKeyDownHandler(event);"/>

The second thing is to use this instruction:

var codigo = event.which || event.keyCode;

This allows us to obtain the code of the key pressed. We use which because the keyCode parameter may not work in all browsers.

If you want to know about the other keys (Escape, Enter, Shift, Etc), you can look at this page , here are examples of the key codes.

About the use of the which and keyCode instruction you can see this link , where it is indicated why.

Scroll to Top