Im relativly new to js so im making a gueessing game from 1 to 100 using Math.random to get my random number. I have a play again button that clears all previous guesses from a previous round but when you click it the random number does not change so the next rounds number is the same
I tried stating random again in the play again function but it did not work and I also tried putting the variable in the function but then it changed upon every guess the user inputed
let random = Math.floor(Math.random() * 101)
console.log(random)
const guess = document.querySelector('.guess')
const button = document.querySelector('.submit')
const myForm = document.querySelector('.myForm')
let numguesses = 0
myForm.addEventListener('submit', click)
function click(e) {
e.preventDefault();
const ul = document.querySelector('.guesses')
if(guess.value > 100 || guess.value < 0 || isNaN(guess.value)) {
alert("please a enter number between 0 to 100")
} else {
numguesses++;
if(random != guess.value) {
if(guess.value > random) {
const eachguess = document.createElement('li')
eachguess.innerText= `${guess.value} was too High`
eachguess.classList.add('wrong')
ul.append(eachguess)
guess.value = '';
} else {
const eachguess = document.createElement('li')
eachguess.innerText = `${guess.value} was too Low`
eachguess.classList.add('low')
ul.append(eachguess)
guess.value = '';
}
} else {
const eachguess = document.createElement('li')
eachguess.innerText = `Well done you gueesed Correctly the number was ${random} it took ${numguesses} guesses`
eachguess.classList.add('correct')
ul.append(eachguess)
guess.value = ''
return
}
}
}
const PlayAgain = document.querySelector('#playAgain')
PlayAgain.addEventListener('click', Play)
function Play() {
const ul = document.querySelector('.guesses')
while (ul.firstChild) {
ul.removeChild(ul.firstChild)
numguesses = 0
}
}
You can assign a new value within the Play function:
let random;
// ...
function Play() {
const ul = document.querySelector('.guesses')
while (ul.firstChild) {
ul.removeChild(ul.firstChild)
}
numguesses = 0
random = Math.floor(Math.random() * 101) // <------
console.log(random)
}
You must not add the let keyword here as that would declare the random variable locally within the Play function - but in your case you want to re-assign the existing variable from the outer scope).