I want to display the results of a rock paper scissors game in a div through DOM methods after clicking a button.
After clicking a button of choice, however, the text like "You Win! rock beats scissors" is only displayed for a short period of time. How do I have the results stay displayed?
I am currently using textContent. However, when I tried innerHTML, the text does not display at all after clicking a button.
html
<html>
<head>
<title>Page Title</title>
<meta charset="UTF-8"/>
</head>
<body>
<form>
<button id="rockBtn">Rock</button>
</form>
<div id="results"></div>
</body>
<script src="main.js"></script>
</html>
javascript
let playerSelection;
function computerPlay(choices =["rock", "paper", "scissors"]) {
const randomIndex = Math.floor(Math.random() * choices.length);
const randomReturn = choices[randomIndex];
return randomReturn;
}
let computerSelection = computerPlay();
function playRound(playerSelection, computerSelection) {
computerSelection = computerPlay();
if (playerSelection.toLowerCase() === "rock") {
if (computerSelection === "paper") {
let resultText = "You Lose! " + computerSelection + " beats " + playerSelection;
computerScore++;
document.getElementById("results").textContent = resultText;
} else if (computerSelection === "scissors") {
let resultText = "You Win! " + playerSelection + " beats " + computerSelection;
playerScore++;
console.log(resultText);
document.getElementById("results").textContent = resultText;
} else if (computerSelection === "rock") {
let resultText = "It's a draw! " + playerSelection + " and " + computerSelection;
console.log(resultText);
document.getElementById("results").textContent = resultText;
}
}
}
document.getElementById("rockBtn").addEventListener("click", function(){
playRound("rock", computerSelection);
});