Home > Blockchain >  addEventLister on a button only works twice and only when window is refreshed
addEventLister on a button only works twice and only when window is refreshed

Time:02-18

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 >Guess the number!</h3>
        <p >Enter a number between 1 - 5 below:</p>
        <input  type="text" id="input-number"
               placeholder="Enter your number here"
               tabindex="1" autofocus >
        <h4  id="result-text">Success!</h4>
         <div >
            <button  id="btn-reset">Reset</button>
            <button  id="btn-guess">Guess</button>
          </div>
    </main>
    <script src="guessthatnumber.js"></script>
</body>
</html>

CodePudding user response:

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

CodePudding user response:

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 >Guess the number!</h3>
  <p >Enter a number between 1 - 5 below:</p>
  <input  type="text" id="input-number" placeholder="Enter your number here" tabindex="1" autofocus>
  <h4  id="result-text">Success!</h4>
  <div >
    <button  id="btn-reset">Reset</button>
    <button  id="btn-guess">Guess</button>
  </div>
</main>

CodePudding user response:

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

</html>

  • Related