• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

100
Vistas
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 3 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda