vendredi 22 janvier 2021

How can I compare scores using if statement and .innerText?

I'm trying to make a Ping Pong scoreKeeper. Everything is done except the part where the scores are compared and a winner is declared. I'm trying to use the if statement to compare the innerText of two variables and whether their scores match or not. But it's not working.

Here's the Javascript and HTML code I've written.

const p1Score = document.querySelector("#p1Score")
const p2Score = document.querySelector("#p2Score")

const increaseP1Score = document.querySelector("#increaseP1Score")
const increaseP2Score = document.querySelector("#increaseP2Score")
const resetScore = document.querySelector("#resetScore")

const scoreKeeper = document.querySelector("#scoreKeeper")

increaseP1Score.addEventListener('click', function(event) {
    p1Score.innerText++
    // if (p1Score.innerText == 5 && p1Score.innerText > p2Score.innerText) {
    // console.log("Here it works!")

})
increaseP2Score.addEventListener('click', function() {
    p2Score.innerText++
})
resetScore.addEventListener('click', function() {
    p1Score.innerText = 0;
    p2Score.innerText = 0;
})

if (p1Score.innerText == 5 && p1Score.innerText > p2Score.innerText) {
    console.log("Working!")
}
 <div id="container">
        <header id="header">
            <h1 id="scoreKeeper">Current Score: <span id="p1Score">0</span> to <span id="p2Score">1</span></h1>
        </header>
        <footer id="footer">
            <button id="increaseP1Score">+1 Player One</button>
            <button id="increaseP2Score">+1 Player Two</button>
            <button id="resetScore">Reset</button>
        </footer>
    </div>

You'll see a comment in my JS code. When I try to compare the values there, it somehow works. But I don't know why it doesn't work outside the event listener.

Aucun commentaire:

Enregistrer un commentaire