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