Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

119
Vistas
addEventLister on a button only works twice and only when window is refreshed

I have two buttons when clicked I want to call functions I wrapped all my function in play() function I tried to an addEventListener to the guess button but it only runs the alert only twice after the window is refreshed.

function play() {

    let numInput = document.getElementById("input-number");
    let resultText = document.getElementById("result-text");
    let btnReset = document.getElementById("btn-reset");
    let btnGuess = document.getElementById("btn-guess");
    let numRandom = null;


    function getRandomNumber(min, max){
        return Math.floor(Math.random() * (max - min + 1)  + min);   
    }

    function guessTheNumber(){
        numRandom = getRandomNumber(1,5);
        numInput = numInput.value;
        alert("button clicked")
    }

    btnGuess.addEventListener("click",function (){
        guessTheNumber();
    });

}

play();
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Guess That Number</title>
    <link rel="stylesheet" href="guessthatnumber.css">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Lato:ital,wght@0,100;0,300;0,400;1,100&display=swap" rel="stylesheet">
</head>
<body>
    <main>
        <h3 class="game-header">Guess the number!</h3>
        <p class="game-instruction">Enter a number between 1 - 5 below:</p>
        <input class="game-input" type="text" id="input-number"
               placeholder="Enter your number here"
               tabindex="1" autofocus >
        <h4 class="game-result" id="result-text">Success!</h4>
         <div class="btn-container">
            <button class="btn-clear" id="btn-reset">Reset</button>
            <button class="btn-guess" id="btn-guess">Guess</button>
          </div>
    </main>
    <script src="guessthatnumber.js"></script>
</body>
</html>

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

It is happening because you are changing numInput value every time button is pressed.. numInput = numInput.value;

first iteration: numInput is equal to value inside an input (lets say it is 5)

so the numInput is 5

second iteration: numInput is equal to numInput.value and since 5 does not have .value attribute, it is undefined and you get error

about 4 years ago · Juan Pablo Isaza Denunciar

0

The issue with the code is in guessTheNumber function.

You are calculating the random number using numRandom = getRandomNumber(1, 5); and in the next line you are assigning numInput = numInput.value;. Here numInput is your input element. You are overwriting that variable with a number. Next time when guessTheNumber executes numInput will be a string and numInput.value will be undefined. Third time you are trying to access value of undefined, this will throws a console error like Uncaught TypeError: Cannot read properties of undefined (reading 'value')

Correct that code segment to make your code stable.

I have commented that section to make the code not broken.

function play() {
  let numInput = document.getElementById("input-number");
  let resultText = document.getElementById("result-text");
  let btnReset = document.getElementById("btn-reset");
  let btnGuess = document.getElementById("btn-guess");
  let numRandom = null;

  function getRandomNumber(min, max) {
    return Math.floor(Math.random() * (max - min + 1) + min);
  }

  function guessTheNumber() {
    numRandom = getRandomNumber(1, 5);
    // numInput = numInput.value;
    console.log(numRandom);
    alert("button clicked")
  }

  btnGuess.addEventListener("click", function () {
    guessTheNumber();
  });
}
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Lato:ital,wght@0,100;0,300;0,400;1,100&display=swap"
  rel="stylesheet">
<main>
  <h3 class="game-header">Guess the number!</h3>
  <p class="game-instruction">Enter a number between 1 - 5 below:</p>
  <input class="game-input" type="text" id="input-number" placeholder="Enter your number here" tabindex="1" autofocus>
  <h4 class="game-result" id="result-text">Success!</h4>
  <div class="btn-container">
    <button class="btn-clear" id="btn-reset">Reset</button>
    <button class="btn-guess" id="btn-guess">Guess</button>
  </div>
</main>

about 4 years ago · Juan Pablo Isaza Denunciar

0

Several things

  1. Calling the variable numInput the same as the field is not a good idea and is the main issue in your code
  2. You did not toggle the success

You can simplify the code by moving the functions outside

const numInput = document.getElementById("input-number"),
  resultText = document.getElementById("result-text"),
  btnReset = document.getElementById("btn-reset"),
  btnGuess = document.getElementById("btn-guess");

function getRandomNumber(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min);
}

function play() {
  let numRandom = getRandomNumber(1, 5);
  let num = +numInput.value;
  resultText.hidden = numRandom != num;
  console.log(numRandom === num ? "you guessed right" : "you guessed wrong")
}
btnGuess.addEventListener("click", play)
btnReset.addEventListener("click", function() {  resultText.hidden = true; numInput.value = ""; })
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Guess That Number</title>
  <link rel="stylesheet" href="guessthatnumber.css">
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Lato:ital,wght@0,100;0,300;0,400;1,100&display=swap" rel="stylesheet">
</head>

<body>
  <main>
    <h3 class="game-header">Guess the number!</h3>
    <p class="game-instruction">Enter a number between 1 - 5 below:</p>
      <input class="game-input" type="text" id="input-number" placeholder="Enter your number here" tabindex="1" autofocus>
      <h4 class="game-result" hidden id="result-text">Success!</h4>
      <div class="btn-container">
        <button class="btn-clear" id="btn-reset">Reset</button>
        <button class="btn-guess" id="btn-guess">Guess</button>
      </div>
  </main>
  <script src="guessthatnumber.js"></script>
</body>

</html>

about 4 years ago · Juan Pablo Isaza Denunciar
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 Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda