On the left is the results from textContent
Just a bit of context from the image. I am trying to manipulate DOM by invoking the textContent to the window everytime the user clicks the button while also logging it in the terminal. However, let's say if I click scissor and then click the rock button quickly after, the textContent resulting from clicking the rock button will not be invoked even though I can see from the terminal that the button has indeed been clicked and logged in the terminal so I need to wait for ~1s every time so the textContent can prints to correct statement. Is there a a way so that I can click the button and the textContent will precisely prints out the desired statement?
const container = document.querySelector(".container")
const content = document.createElement('div')
content.classList.add('result')
container.appendChild(content)
const buttons = document.querySelectorAll('button')
buttons.forEach(button => button.addEventListener('click', playGame));
function computerPlay() {
let responses = ["rock", "paper", "scissor"];
response = responses[Math.floor(Math.random() * responses.length)];
return response;
// console.log(response)
}
function playGame(e) {
let userScore = 0
let computerScore = 0
playerResponse = e.target.className;
computerSelection = computerPlay()
console.log(playerResponse)
// console.log(computerSelection)
// for (let i = userScore; i < 5; i ){
if (playerResponse == 'scissor' && computerSelection == 'paper') {
// console.log("It's a tie!")
content.textContent = "You win! Scissor beats paper"
} else if (playerResponse == "paper" && computerSelection == "rock") {
userScore
// console.log("You win, scissor beats paper")
content.textContent = "You win! Paper beats rock"
} else if (playerResponse == "rock" && computerSelection == "scissor") {
userScore
// console.log("You win, rock beats scissor")
content.textContent = "You win! Rock beats scissor"
} else if (playerResponse === computerSelection) {
// console.log("You win, paper beats rock")
content.textContent = `You both choose ${playerResponse}, it's a tie!`
} else {
computerScore
// console.log("You lose, try again!")
content.texContent = "You lose, try again!!"
}
// }
// console.log(computerScore)
// console.log(userScore)
}
I'm still new to JS so the code is really messy.
CodePudding user response:
The problem is that u only assign a new String value to the content.textContent, but u dont update the DOM node immediately after it.
Put following code options on the bottom of your playgame() function
Adding another message: U have to do container.appendChild(content) again if u want to add another message.
Updating the message: U can update the text om the screen easy by editing the innerHTML of the current DOM node for example.
document.querySelector(".result").innerHTML = content.textContent;