How To Print All Keystrokes On Screen With Js?
I am working on a hangman type of game and I got the keystrokes to display on screen, but they seem to overwrite each other each time I hit a key. How can I display every keystroke
Solution 1:
The overwrite is occuring upon assigning lettersGuessed
rather than appending them.
Assigning: (wrong behavior)
document.getElementById("lettersGuessed").innerHTML = lettersGuessed;
Appending: (correct behavior)
document.getElementById("lettersGuessed").innerHTML += lettersGuessed;
After that you can see the following result:
//Possible words to guessvar words = ['jason', 'kaitlyn', 'lora', 'matthew'];
//Computer picks random word to guessfunctiongetItem() {
document.getElementById("wordGuess").innerHTML = words[Math.floor(Math.random() * words.length)];
}
//This code captures the keypress and prints it out on the screenvar guessesLeft = 9;
document.onkeypress = function(evt) {
var evt = evt || window.event;
var charCode = evt.keyCode || evt.which;
var lettersGuessed = String.fromCharCode(charCode);
document.getElementById("lettersGuessed").innerHTML += lettersGuessed;
document.getElementById("guessesLeft").innerHTML = guessesLeft;
guessesLeft--;
// var userGuess = prompt("What word do you guess?");// if (words.indexOf(userGuess) > -1){// alert("Your guess is correct.")// }else{// alert("Your guess is wrong.")// }if (guessesLeft === -1) {
alert("You Loose!");
}
};
<!-- Example HTML code ---><divid="wordGuess">abcdefg</div><divid="lettersGuessed"></div><divid="guessesLeft"></div>
Solution 2:
You are overwriting #lettersGuessed
on each key press. You should do something like:
document.getElementById("lettersGuessed").innerHTML += lettersGuessed;
But I would suggest adding the letters to an array and checking everything from there.
Post a Comment for "How To Print All Keystrokes On Screen With Js?"