Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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;
}
while(1===1){
    document.onkeypress(keys());
}

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
}
while(1===1){
    document.onkeypress(keys())
}

just doesn’t work nicely.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading