Write keypresses to the DOM

So, I am trying to run a function that grabs the key that was pressed and puts it in a variable.
I have tried doing:

let text = "";
function keys(){
    let key = KeyboardEvent.name;
    text = text + key;
    document.querySelector("#text").innerHTML = text;

But it hasn’t thrown any errors at me and isn’t doing what I want it to do. I would like to ask someone to explain to me how I can change and fix it.

let text = ""
function keys(){
    let key = KeyboardEvent.name
    text = text + key
    document.querySelector("#text").innerHTML = text

just doesn’t work nicely.

>Solution :

You can get the key pressed using event.key in the keypress event handler.

document.addEventListener('keypress', e => {
  document.getElementById('key').textContent = e.key;
<p id="key"></p>

Leave a Reply