Quantcast
Channel: Active questions tagged html - Stack Overflow
Viewing all articles
Browse latest Browse all 67497

The EventListener I put on my buttons does not work on the first click

$
0
0

The only problem I have with this code is that it won't start incrementing my numbers when I click on the "Player One" button or on the "Player Two" button. Everything else works it's just that I have to click twice to have it start incrementing. Is there a way I could just have it do that from the first click?

<!DOCTYPE html>
<html>
<head>
    <title>Score Keeper</title>
    <script type="text/javascript" src="script.js"></script>
</head>
<body>
    <h1><span id="player1Score">0</span> to <span id="player2Score">0</span></h1>
    <p>Playing to: <span id="matchScore">5</span></p>
    <div>
        <input type="number" name="matchScore">
        <button>Player One</button>
        <button>Player Two</button>
        <button>Reset</button>
    </div>
</body>
</html>
window.setTimeout(function() {
    var player1Score = 0
    var player2Score = 0
    var buttP1 = document.querySelector("button")
    var buttP2 = document.querySelectorAll("button")[1]
    var buttReset = document.querySelectorAll("button")[2]
    var inputMatchScore = document.querySelector("input")

    buttP1.addEventListener("click", function(){
        if(document.getElementById("player1Score").textContent < Number(document.getElementById("matchScore").textContent)){
            document.getElementById("player1Score").textContent = player1Score++
        }
    })
    buttP2.addEventListener("click", function(){
        if(document.getElementById("player2Score").textContent < Number(document.getElementById("matchScore").textContent)){
            document.getElementById("player2Score").textContent = player2Score++
        }
    })
    buttReset.addEventListener("click", function(){
        document.getElementById("player1Score").textContent = 0
        document.getElementById("player2Score").textContent = 0
        player1Score = 0
        player2Score = 0
    })
    inputMatchScore.addEventListener("input", function(){
        document.getElementById("matchScore").textContent = document.querySelector("input").value
    })
}, 500);

Viewing all articles
Browse latest Browse all 67497

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>