Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

132
Views
My function is being run before a button is clicked

I'm trying to loop through each button to check if it's been clicked, and if a button has, then call the test() function. However, the function is called and "test" is logged in the console three times before any button is even pressed. Why is the function being ran before the user presses a button?

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Rock, Paper, Scissors</title>
    </head>

    <body>
        <h1>Rock, Paper, Scissors!</h1>
        <button id="ROCK">Rock!</button>
        <button id="PAPER">Paper!</button>
        <button id="SCISSORS">Scissors!</button>

        <script src="javascript.js"></script>
    </body>
</html>

function test() {
    console.log('test');
}
function playGame() {

    //check whether user has clicked button
    const btn = document.querySelectorAll('button');
    btn.forEach(button => {
        button.addEventListener("click", test())});  
}
    
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!