I have two files, 1 html and 1 javascript. I am trying to add a streak function so when a answer is guessed correctly the streak goes up by 1 if one question is guessed wrong the counter goes back to 0. I have tried to add a div in the html file and tried to call it in another javascript file by getting document by ID and then writing a simple counter function, but that appears not to work.
The code below is where i want to add my counter. So in the last return "Great work! You guessed the word!" that is where the counter should start counting and showing up in a div/span/p in the html file. Any suggestions?
Note the var is meant to be streak/counter instead of clicks
get statusMessage(){
var streak=0;
if (this.status === 'playing'){
return `Guesses left: ${this.remainingGuesses}`
} else if (this.status === 'failed') {
streak=0;
document.getElementById("streak").innerHTML = streak;
return `Nice try! The word was "${this.word.join('')}"
`
} else {
return 'Great work! You guessed the word!'
streak = 1;
document.getElementById("streak").innerHTML = streak;
}
}
CodePudding user response:
When you return
the following code will not be executed.
So in the following snippet
else {
return 'Great work! You guessed the word!'
streak = 1;
document.getElementById("streak").innerHTML = streak;
}
the streak =1
and the document manipulation will not run.
Just move the return
after the code you want to run.
else {
streak = 1;
document.getElementById("streak").innerHTML = streak;
return 'Great work! You guessed the word!'
}
Of course, you will also have to put the streak
variable somewhere where it is not reset on each call of the statusMessage
method. Maybe define it in the game class.
CodePudding user response:
Because you have var streak=0;
inside the function every time it gets called it sets the variable back to 0. You should move it outside the function. You also return before incrementing the streak variable, so move that line down.
Like this:
var streak = 0;
get statusMessage() {
if (this.status === 'playing'){
return `Guesses left: ${this.remainingGuesses}`
} else if (this.status === 'failed') {
streak=0;
document.getElementById("streak").innerHTML = streak;
return `Nice try! The word was "${this.word.join('')}"
} else {
streak ;
document.getElementById("streak").innerHTML = streak;
return 'Great work! You guessed the word!'
}
}
Also you can use streak ;
to increment a variable by 1.
CodePudding user response:
So i dont know if its the best way to add a counter like this but, streak.innerHTML = 0 sets the div to 0 and streak.innerHTML adds 1 everytime the answer is guessed correctly
get statusMessage() {
if (this.status === 'playing'){
return `Nice try! The word was "${this.word.join('')}"`
return `Guesses left: ${this.remainingGuesses}`
} else if (this.status === 'failed') {
streak.innerHTML = 0
return `Nice try! The word was "${this.word.join('')}"```
} else {
streak.innerHTML
return 'Great work! You guessed the word!'
}
}