if i write like so, things work
var p1Button = document.getElementById("p1Button");
var p1Score = 0;
var p1Span = document.getElementById("p1ScoreSpan");
var p2Button = document.getElementById("p2Button");
var p2Score = 0;
var p2Span = document.getElementById("p2ScoreSpan");
var winningScore = document.querySelector("#targetScore").textContent
var gameOver = false;
//for the reset button
var resetButton = document.getElementById("ResetButton");
p1Button.addEventListener("click", function(){
// console.log(gameOver)
if(!gameOver) {
p1Score++;
if(p1Score == winningScore) {
p1Span.classList.add('winner');
gameOver = true;
}
p1Span.textContent = p1Score;
}
})
p2Button.addEventListener("click", function () {
console.log(gameOver)
if (!gameOver) {
p2Score++;
if(p2Score == winningScore){
p2Span.classList.add('winner');
gameOver = true;
}}
p2Span.textContent = p2Score;
})
But to keep it 'DRY' creating a function and using it as the callback doesn't seem to work. Below is the code snippet, that runs ones even without me clicking the 'buttons' defined in HTML
var callBackfunct = function (playerScore, playerSpan) {
console.log(gameOver)
console.log(winningScore)
if (!gameOver) {
playerScore++;
if (playerScore == winningScore) {
playerSpan.classList.add('winner');
gameOver = true;
}
}
playerSpan.textContent = playerScore;
console.log(gameOver)
}
p1Button.addEventListener("click", callBackfunct(p1Score, p1Span));
p2Button.addEventListener("click", callBackfunct(p2Score, p2Span));
Where did i err'ed? I am expecting that when i click on the player1 button, the callback function is called by hnouring the if conditions