Variable tracking user attempts does not update












0















I am working on a quiz game, and I have been having this issue for a while and I just can't figure out what I am doing wrong. Ask any question if you are confused by my explanation, i will be monitoring this post



How to recreate the problem - Type in the name displayed on the screen until you see "Game over bro!" -
Problem:
when I type in the name in the input field and click "Answer" to check if the input field value matches the name retrieved from the API, there is a variable(var attempts = 5) tracking how many times the user has attempted the question,but this variable(attempts) reduces it's value by one when the answer is correct, it should only do that when the answer is incorrect.



Also, let me know what you think about the JS code, is it bad code?
I am asking because the code in newReq function i wrote it twice, one loads and displays the data retrieved from the API when the page loads, the code inside the newReq function loads a new character when "New character" button is clicked.I was thinking about DRY the whole time, but i'm not sure how to load a new character without re-writing the code






var attemptsPara = document.querySelector("#attempts"),
attempts = 5,
scorePara = document.querySelector("#score"),
score = 0,
feedBackDiv = document.querySelector("#feedBack"),
newCharacterBtn = document.querySelector("#newCharacter"),
answerBtn = document.querySelector("#answer"),
input = document.querySelector("input");

scorePara.textContent = `Score is currently: ${score}`;
attemptsPara.textContent = `${attempts} attempts remaining`;

var feedBackText = document.createElement("p");

var characterPara = document.querySelector("#character");

//click new character button to load new character
// newCharacterBtn.addEventListener("click", () => {
// answerBtn.disabled = false;
// attempts = 5;
// attemptsPara.textContent = `${attempts} attempts remaining`;
// });

//function that displays retrieved data to the DOM
function displayCharacters(info) {
let englishName = info.attributes.name;
characterPara.textContent = `This is the character's name: ${englishName}`;
console.log(englishName, randomNumber);
}


//load new character
var randomNumber = Math.round(Math.random() * 100 + 2);
var request = new XMLHttpRequest();
request.open(
"GET",
"https://kitsu.io/api/edge/characters/" + randomNumber,
true
);

request.send();

request.onload = function() {
var data = JSON.parse(this.response);
var info = data.data;
displayCharacters(info);

//checks if the input value matches name retrieved
answerBtn.addEventListener("click", () => {
let englishName = info.attributes.name;
if (input.value === englishName) {
feedBackText.textContent = `${input.value} is correct`;
feedBackDiv.append(feedBackText);
feedBackDiv.style.backgroundColor = "green";
feedBackDiv.style.display = "block";
setTimeout(() => {
feedBackDiv.style.display = "none";
}, 3000);
score = score + 5;
scorePara.textContent = `Score is currently: ${score}`;
attempts = 5;
attemptsPara.textContent = `${attempts} attempts remaining`;
input.value = "";
newReq(); //call function to load and display new character
} else {
feedBackText.textContent = `${input.value} is wrong`;
feedBackDiv.append(feedBackText);
feedBackDiv.style.backgroundColor = "red";
feedBackDiv.style.display = "block";
input.focus();
setTimeout(() => {
feedBackDiv.style.display = "none";
}, 2000);
attempts = attempts - 1;
attemptsPara.textContent = `${attempts} attempts remaining`;

if (attempts <= 0) {
answerBtn.disabled = true;
attemptsPara.textContent = `Game over bro!`;
}
}
console.log(attempts); //check how many attempts remaining every time answerBtn is clicked
});
};

newCharacterBtn.addEventListener("click", newReq);

//function to make a new request and display it the information on the DOM,when New character button is clicked
function newReq() {
rand = randomNumber = Math.round(Math.random() * 100 + 2);
var request = new XMLHttpRequest();
request.open(
"GET",
"https://kitsu.io/api/edge/characters/" + randomNumber,
true
);

request.send();

request.onload = function() {
var data = JSON.parse(this.response);
var info = data.data;
displayCharacters(info);

answerBtn.addEventListener("click", () => {
let englishName = info.attributes.name;
if (input.value === englishName) {
feedBackText.textContent = `${input.value} is correct`;
feedBackDiv.append(feedBackText);
feedBackDiv.style.backgroundColor = "green";
feedBackDiv.style.display = "block";
//settimeout to hide feedBack div
setTimeout(() => {
feedBackDiv.style.display = "none";
}, 3000);
score = score + 5;
scorePara.textContent = `Score is currently: ${score}`;
attempts = 5;
attemptsPara.textContent = `${attempts} attempts remaining`;
input.value = "";
newReq();
} else if (input.value != englishName) {
feedBackText.textContent = `${input.value} is wrong`;
feedBackDiv.append(feedBackText);
feedBackDiv.style.backgroundColor = "red";
feedBackDiv.style.display = "block";
input.focus();
//settimeout to hide feedBack div
setTimeout(() => {
feedBackDiv.style.display = "none";
}, 2000);
attempts = attempts - 1;
attemptsPara.textContent = `${attempts} attempts remaining`;

if (attempts <= 0) {
answerBtn.disabled = true;
attemptsPara.textContent = `Game over bro!`;
}
}
});
console.log(attempts);
};
}

body {
margin: 0;
padding: 0;
background: black;
}

#imageHolder {
height: 560px;
width: 1100px;
background: #098;
margin: 10px auto;
}

#buttonHolder {
/* background: #453; */
width: 160px;
margin: 0 auto;
}

p,
h3 {
color: yellowgreen;
text-align: center;
}

h3 {
text-decoration: underline;
}

img {
width: 100%;
height: 100%;
}

button,
input {
margin: 10px 10px;
border: none;
background: #098;
display: block;
}

input {
background: white;
}


/* for the question and awnswer game */

#feedBack {
background: #098;
height: 120px;
width: 320px;
margin: 10px auto;
display: none;
}

<p id="score"></p>

<p id="character"></p>

<input type="text"> <button id="answer">Answer</button> <button id="newCharacter">New Character</button>

<p id="attempts"></p>

<div id="feedBack">

</div>












share|improve this question



























    0















    I am working on a quiz game, and I have been having this issue for a while and I just can't figure out what I am doing wrong. Ask any question if you are confused by my explanation, i will be monitoring this post



    How to recreate the problem - Type in the name displayed on the screen until you see "Game over bro!" -
    Problem:
    when I type in the name in the input field and click "Answer" to check if the input field value matches the name retrieved from the API, there is a variable(var attempts = 5) tracking how many times the user has attempted the question,but this variable(attempts) reduces it's value by one when the answer is correct, it should only do that when the answer is incorrect.



    Also, let me know what you think about the JS code, is it bad code?
    I am asking because the code in newReq function i wrote it twice, one loads and displays the data retrieved from the API when the page loads, the code inside the newReq function loads a new character when "New character" button is clicked.I was thinking about DRY the whole time, but i'm not sure how to load a new character without re-writing the code






    var attemptsPara = document.querySelector("#attempts"),
    attempts = 5,
    scorePara = document.querySelector("#score"),
    score = 0,
    feedBackDiv = document.querySelector("#feedBack"),
    newCharacterBtn = document.querySelector("#newCharacter"),
    answerBtn = document.querySelector("#answer"),
    input = document.querySelector("input");

    scorePara.textContent = `Score is currently: ${score}`;
    attemptsPara.textContent = `${attempts} attempts remaining`;

    var feedBackText = document.createElement("p");

    var characterPara = document.querySelector("#character");

    //click new character button to load new character
    // newCharacterBtn.addEventListener("click", () => {
    // answerBtn.disabled = false;
    // attempts = 5;
    // attemptsPara.textContent = `${attempts} attempts remaining`;
    // });

    //function that displays retrieved data to the DOM
    function displayCharacters(info) {
    let englishName = info.attributes.name;
    characterPara.textContent = `This is the character's name: ${englishName}`;
    console.log(englishName, randomNumber);
    }


    //load new character
    var randomNumber = Math.round(Math.random() * 100 + 2);
    var request = new XMLHttpRequest();
    request.open(
    "GET",
    "https://kitsu.io/api/edge/characters/" + randomNumber,
    true
    );

    request.send();

    request.onload = function() {
    var data = JSON.parse(this.response);
    var info = data.data;
    displayCharacters(info);

    //checks if the input value matches name retrieved
    answerBtn.addEventListener("click", () => {
    let englishName = info.attributes.name;
    if (input.value === englishName) {
    feedBackText.textContent = `${input.value} is correct`;
    feedBackDiv.append(feedBackText);
    feedBackDiv.style.backgroundColor = "green";
    feedBackDiv.style.display = "block";
    setTimeout(() => {
    feedBackDiv.style.display = "none";
    }, 3000);
    score = score + 5;
    scorePara.textContent = `Score is currently: ${score}`;
    attempts = 5;
    attemptsPara.textContent = `${attempts} attempts remaining`;
    input.value = "";
    newReq(); //call function to load and display new character
    } else {
    feedBackText.textContent = `${input.value} is wrong`;
    feedBackDiv.append(feedBackText);
    feedBackDiv.style.backgroundColor = "red";
    feedBackDiv.style.display = "block";
    input.focus();
    setTimeout(() => {
    feedBackDiv.style.display = "none";
    }, 2000);
    attempts = attempts - 1;
    attemptsPara.textContent = `${attempts} attempts remaining`;

    if (attempts <= 0) {
    answerBtn.disabled = true;
    attemptsPara.textContent = `Game over bro!`;
    }
    }
    console.log(attempts); //check how many attempts remaining every time answerBtn is clicked
    });
    };

    newCharacterBtn.addEventListener("click", newReq);

    //function to make a new request and display it the information on the DOM,when New character button is clicked
    function newReq() {
    rand = randomNumber = Math.round(Math.random() * 100 + 2);
    var request = new XMLHttpRequest();
    request.open(
    "GET",
    "https://kitsu.io/api/edge/characters/" + randomNumber,
    true
    );

    request.send();

    request.onload = function() {
    var data = JSON.parse(this.response);
    var info = data.data;
    displayCharacters(info);

    answerBtn.addEventListener("click", () => {
    let englishName = info.attributes.name;
    if (input.value === englishName) {
    feedBackText.textContent = `${input.value} is correct`;
    feedBackDiv.append(feedBackText);
    feedBackDiv.style.backgroundColor = "green";
    feedBackDiv.style.display = "block";
    //settimeout to hide feedBack div
    setTimeout(() => {
    feedBackDiv.style.display = "none";
    }, 3000);
    score = score + 5;
    scorePara.textContent = `Score is currently: ${score}`;
    attempts = 5;
    attemptsPara.textContent = `${attempts} attempts remaining`;
    input.value = "";
    newReq();
    } else if (input.value != englishName) {
    feedBackText.textContent = `${input.value} is wrong`;
    feedBackDiv.append(feedBackText);
    feedBackDiv.style.backgroundColor = "red";
    feedBackDiv.style.display = "block";
    input.focus();
    //settimeout to hide feedBack div
    setTimeout(() => {
    feedBackDiv.style.display = "none";
    }, 2000);
    attempts = attempts - 1;
    attemptsPara.textContent = `${attempts} attempts remaining`;

    if (attempts <= 0) {
    answerBtn.disabled = true;
    attemptsPara.textContent = `Game over bro!`;
    }
    }
    });
    console.log(attempts);
    };
    }

    body {
    margin: 0;
    padding: 0;
    background: black;
    }

    #imageHolder {
    height: 560px;
    width: 1100px;
    background: #098;
    margin: 10px auto;
    }

    #buttonHolder {
    /* background: #453; */
    width: 160px;
    margin: 0 auto;
    }

    p,
    h3 {
    color: yellowgreen;
    text-align: center;
    }

    h3 {
    text-decoration: underline;
    }

    img {
    width: 100%;
    height: 100%;
    }

    button,
    input {
    margin: 10px 10px;
    border: none;
    background: #098;
    display: block;
    }

    input {
    background: white;
    }


    /* for the question and awnswer game */

    #feedBack {
    background: #098;
    height: 120px;
    width: 320px;
    margin: 10px auto;
    display: none;
    }

    <p id="score"></p>

    <p id="character"></p>

    <input type="text"> <button id="answer">Answer</button> <button id="newCharacter">New Character</button>

    <p id="attempts"></p>

    <div id="feedBack">

    </div>












    share|improve this question

























      0












      0








      0








      I am working on a quiz game, and I have been having this issue for a while and I just can't figure out what I am doing wrong. Ask any question if you are confused by my explanation, i will be monitoring this post



      How to recreate the problem - Type in the name displayed on the screen until you see "Game over bro!" -
      Problem:
      when I type in the name in the input field and click "Answer" to check if the input field value matches the name retrieved from the API, there is a variable(var attempts = 5) tracking how many times the user has attempted the question,but this variable(attempts) reduces it's value by one when the answer is correct, it should only do that when the answer is incorrect.



      Also, let me know what you think about the JS code, is it bad code?
      I am asking because the code in newReq function i wrote it twice, one loads and displays the data retrieved from the API when the page loads, the code inside the newReq function loads a new character when "New character" button is clicked.I was thinking about DRY the whole time, but i'm not sure how to load a new character without re-writing the code






      var attemptsPara = document.querySelector("#attempts"),
      attempts = 5,
      scorePara = document.querySelector("#score"),
      score = 0,
      feedBackDiv = document.querySelector("#feedBack"),
      newCharacterBtn = document.querySelector("#newCharacter"),
      answerBtn = document.querySelector("#answer"),
      input = document.querySelector("input");

      scorePara.textContent = `Score is currently: ${score}`;
      attemptsPara.textContent = `${attempts} attempts remaining`;

      var feedBackText = document.createElement("p");

      var characterPara = document.querySelector("#character");

      //click new character button to load new character
      // newCharacterBtn.addEventListener("click", () => {
      // answerBtn.disabled = false;
      // attempts = 5;
      // attemptsPara.textContent = `${attempts} attempts remaining`;
      // });

      //function that displays retrieved data to the DOM
      function displayCharacters(info) {
      let englishName = info.attributes.name;
      characterPara.textContent = `This is the character's name: ${englishName}`;
      console.log(englishName, randomNumber);
      }


      //load new character
      var randomNumber = Math.round(Math.random() * 100 + 2);
      var request = new XMLHttpRequest();
      request.open(
      "GET",
      "https://kitsu.io/api/edge/characters/" + randomNumber,
      true
      );

      request.send();

      request.onload = function() {
      var data = JSON.parse(this.response);
      var info = data.data;
      displayCharacters(info);

      //checks if the input value matches name retrieved
      answerBtn.addEventListener("click", () => {
      let englishName = info.attributes.name;
      if (input.value === englishName) {
      feedBackText.textContent = `${input.value} is correct`;
      feedBackDiv.append(feedBackText);
      feedBackDiv.style.backgroundColor = "green";
      feedBackDiv.style.display = "block";
      setTimeout(() => {
      feedBackDiv.style.display = "none";
      }, 3000);
      score = score + 5;
      scorePara.textContent = `Score is currently: ${score}`;
      attempts = 5;
      attemptsPara.textContent = `${attempts} attempts remaining`;
      input.value = "";
      newReq(); //call function to load and display new character
      } else {
      feedBackText.textContent = `${input.value} is wrong`;
      feedBackDiv.append(feedBackText);
      feedBackDiv.style.backgroundColor = "red";
      feedBackDiv.style.display = "block";
      input.focus();
      setTimeout(() => {
      feedBackDiv.style.display = "none";
      }, 2000);
      attempts = attempts - 1;
      attemptsPara.textContent = `${attempts} attempts remaining`;

      if (attempts <= 0) {
      answerBtn.disabled = true;
      attemptsPara.textContent = `Game over bro!`;
      }
      }
      console.log(attempts); //check how many attempts remaining every time answerBtn is clicked
      });
      };

      newCharacterBtn.addEventListener("click", newReq);

      //function to make a new request and display it the information on the DOM,when New character button is clicked
      function newReq() {
      rand = randomNumber = Math.round(Math.random() * 100 + 2);
      var request = new XMLHttpRequest();
      request.open(
      "GET",
      "https://kitsu.io/api/edge/characters/" + randomNumber,
      true
      );

      request.send();

      request.onload = function() {
      var data = JSON.parse(this.response);
      var info = data.data;
      displayCharacters(info);

      answerBtn.addEventListener("click", () => {
      let englishName = info.attributes.name;
      if (input.value === englishName) {
      feedBackText.textContent = `${input.value} is correct`;
      feedBackDiv.append(feedBackText);
      feedBackDiv.style.backgroundColor = "green";
      feedBackDiv.style.display = "block";
      //settimeout to hide feedBack div
      setTimeout(() => {
      feedBackDiv.style.display = "none";
      }, 3000);
      score = score + 5;
      scorePara.textContent = `Score is currently: ${score}`;
      attempts = 5;
      attemptsPara.textContent = `${attempts} attempts remaining`;
      input.value = "";
      newReq();
      } else if (input.value != englishName) {
      feedBackText.textContent = `${input.value} is wrong`;
      feedBackDiv.append(feedBackText);
      feedBackDiv.style.backgroundColor = "red";
      feedBackDiv.style.display = "block";
      input.focus();
      //settimeout to hide feedBack div
      setTimeout(() => {
      feedBackDiv.style.display = "none";
      }, 2000);
      attempts = attempts - 1;
      attemptsPara.textContent = `${attempts} attempts remaining`;

      if (attempts <= 0) {
      answerBtn.disabled = true;
      attemptsPara.textContent = `Game over bro!`;
      }
      }
      });
      console.log(attempts);
      };
      }

      body {
      margin: 0;
      padding: 0;
      background: black;
      }

      #imageHolder {
      height: 560px;
      width: 1100px;
      background: #098;
      margin: 10px auto;
      }

      #buttonHolder {
      /* background: #453; */
      width: 160px;
      margin: 0 auto;
      }

      p,
      h3 {
      color: yellowgreen;
      text-align: center;
      }

      h3 {
      text-decoration: underline;
      }

      img {
      width: 100%;
      height: 100%;
      }

      button,
      input {
      margin: 10px 10px;
      border: none;
      background: #098;
      display: block;
      }

      input {
      background: white;
      }


      /* for the question and awnswer game */

      #feedBack {
      background: #098;
      height: 120px;
      width: 320px;
      margin: 10px auto;
      display: none;
      }

      <p id="score"></p>

      <p id="character"></p>

      <input type="text"> <button id="answer">Answer</button> <button id="newCharacter">New Character</button>

      <p id="attempts"></p>

      <div id="feedBack">

      </div>












      share|improve this question














      I am working on a quiz game, and I have been having this issue for a while and I just can't figure out what I am doing wrong. Ask any question if you are confused by my explanation, i will be monitoring this post



      How to recreate the problem - Type in the name displayed on the screen until you see "Game over bro!" -
      Problem:
      when I type in the name in the input field and click "Answer" to check if the input field value matches the name retrieved from the API, there is a variable(var attempts = 5) tracking how many times the user has attempted the question,but this variable(attempts) reduces it's value by one when the answer is correct, it should only do that when the answer is incorrect.



      Also, let me know what you think about the JS code, is it bad code?
      I am asking because the code in newReq function i wrote it twice, one loads and displays the data retrieved from the API when the page loads, the code inside the newReq function loads a new character when "New character" button is clicked.I was thinking about DRY the whole time, but i'm not sure how to load a new character without re-writing the code






      var attemptsPara = document.querySelector("#attempts"),
      attempts = 5,
      scorePara = document.querySelector("#score"),
      score = 0,
      feedBackDiv = document.querySelector("#feedBack"),
      newCharacterBtn = document.querySelector("#newCharacter"),
      answerBtn = document.querySelector("#answer"),
      input = document.querySelector("input");

      scorePara.textContent = `Score is currently: ${score}`;
      attemptsPara.textContent = `${attempts} attempts remaining`;

      var feedBackText = document.createElement("p");

      var characterPara = document.querySelector("#character");

      //click new character button to load new character
      // newCharacterBtn.addEventListener("click", () => {
      // answerBtn.disabled = false;
      // attempts = 5;
      // attemptsPara.textContent = `${attempts} attempts remaining`;
      // });

      //function that displays retrieved data to the DOM
      function displayCharacters(info) {
      let englishName = info.attributes.name;
      characterPara.textContent = `This is the character's name: ${englishName}`;
      console.log(englishName, randomNumber);
      }


      //load new character
      var randomNumber = Math.round(Math.random() * 100 + 2);
      var request = new XMLHttpRequest();
      request.open(
      "GET",
      "https://kitsu.io/api/edge/characters/" + randomNumber,
      true
      );

      request.send();

      request.onload = function() {
      var data = JSON.parse(this.response);
      var info = data.data;
      displayCharacters(info);

      //checks if the input value matches name retrieved
      answerBtn.addEventListener("click", () => {
      let englishName = info.attributes.name;
      if (input.value === englishName) {
      feedBackText.textContent = `${input.value} is correct`;
      feedBackDiv.append(feedBackText);
      feedBackDiv.style.backgroundColor = "green";
      feedBackDiv.style.display = "block";
      setTimeout(() => {
      feedBackDiv.style.display = "none";
      }, 3000);
      score = score + 5;
      scorePara.textContent = `Score is currently: ${score}`;
      attempts = 5;
      attemptsPara.textContent = `${attempts} attempts remaining`;
      input.value = "";
      newReq(); //call function to load and display new character
      } else {
      feedBackText.textContent = `${input.value} is wrong`;
      feedBackDiv.append(feedBackText);
      feedBackDiv.style.backgroundColor = "red";
      feedBackDiv.style.display = "block";
      input.focus();
      setTimeout(() => {
      feedBackDiv.style.display = "none";
      }, 2000);
      attempts = attempts - 1;
      attemptsPara.textContent = `${attempts} attempts remaining`;

      if (attempts <= 0) {
      answerBtn.disabled = true;
      attemptsPara.textContent = `Game over bro!`;
      }
      }
      console.log(attempts); //check how many attempts remaining every time answerBtn is clicked
      });
      };

      newCharacterBtn.addEventListener("click", newReq);

      //function to make a new request and display it the information on the DOM,when New character button is clicked
      function newReq() {
      rand = randomNumber = Math.round(Math.random() * 100 + 2);
      var request = new XMLHttpRequest();
      request.open(
      "GET",
      "https://kitsu.io/api/edge/characters/" + randomNumber,
      true
      );

      request.send();

      request.onload = function() {
      var data = JSON.parse(this.response);
      var info = data.data;
      displayCharacters(info);

      answerBtn.addEventListener("click", () => {
      let englishName = info.attributes.name;
      if (input.value === englishName) {
      feedBackText.textContent = `${input.value} is correct`;
      feedBackDiv.append(feedBackText);
      feedBackDiv.style.backgroundColor = "green";
      feedBackDiv.style.display = "block";
      //settimeout to hide feedBack div
      setTimeout(() => {
      feedBackDiv.style.display = "none";
      }, 3000);
      score = score + 5;
      scorePara.textContent = `Score is currently: ${score}`;
      attempts = 5;
      attemptsPara.textContent = `${attempts} attempts remaining`;
      input.value = "";
      newReq();
      } else if (input.value != englishName) {
      feedBackText.textContent = `${input.value} is wrong`;
      feedBackDiv.append(feedBackText);
      feedBackDiv.style.backgroundColor = "red";
      feedBackDiv.style.display = "block";
      input.focus();
      //settimeout to hide feedBack div
      setTimeout(() => {
      feedBackDiv.style.display = "none";
      }, 2000);
      attempts = attempts - 1;
      attemptsPara.textContent = `${attempts} attempts remaining`;

      if (attempts <= 0) {
      answerBtn.disabled = true;
      attemptsPara.textContent = `Game over bro!`;
      }
      }
      });
      console.log(attempts);
      };
      }

      body {
      margin: 0;
      padding: 0;
      background: black;
      }

      #imageHolder {
      height: 560px;
      width: 1100px;
      background: #098;
      margin: 10px auto;
      }

      #buttonHolder {
      /* background: #453; */
      width: 160px;
      margin: 0 auto;
      }

      p,
      h3 {
      color: yellowgreen;
      text-align: center;
      }

      h3 {
      text-decoration: underline;
      }

      img {
      width: 100%;
      height: 100%;
      }

      button,
      input {
      margin: 10px 10px;
      border: none;
      background: #098;
      display: block;
      }

      input {
      background: white;
      }


      /* for the question and awnswer game */

      #feedBack {
      background: #098;
      height: 120px;
      width: 320px;
      margin: 10px auto;
      display: none;
      }

      <p id="score"></p>

      <p id="character"></p>

      <input type="text"> <button id="answer">Answer</button> <button id="newCharacter">New Character</button>

      <p id="attempts"></p>

      <div id="feedBack">

      </div>








      var attemptsPara = document.querySelector("#attempts"),
      attempts = 5,
      scorePara = document.querySelector("#score"),
      score = 0,
      feedBackDiv = document.querySelector("#feedBack"),
      newCharacterBtn = document.querySelector("#newCharacter"),
      answerBtn = document.querySelector("#answer"),
      input = document.querySelector("input");

      scorePara.textContent = `Score is currently: ${score}`;
      attemptsPara.textContent = `${attempts} attempts remaining`;

      var feedBackText = document.createElement("p");

      var characterPara = document.querySelector("#character");

      //click new character button to load new character
      // newCharacterBtn.addEventListener("click", () => {
      // answerBtn.disabled = false;
      // attempts = 5;
      // attemptsPara.textContent = `${attempts} attempts remaining`;
      // });

      //function that displays retrieved data to the DOM
      function displayCharacters(info) {
      let englishName = info.attributes.name;
      characterPara.textContent = `This is the character's name: ${englishName}`;
      console.log(englishName, randomNumber);
      }


      //load new character
      var randomNumber = Math.round(Math.random() * 100 + 2);
      var request = new XMLHttpRequest();
      request.open(
      "GET",
      "https://kitsu.io/api/edge/characters/" + randomNumber,
      true
      );

      request.send();

      request.onload = function() {
      var data = JSON.parse(this.response);
      var info = data.data;
      displayCharacters(info);

      //checks if the input value matches name retrieved
      answerBtn.addEventListener("click", () => {
      let englishName = info.attributes.name;
      if (input.value === englishName) {
      feedBackText.textContent = `${input.value} is correct`;
      feedBackDiv.append(feedBackText);
      feedBackDiv.style.backgroundColor = "green";
      feedBackDiv.style.display = "block";
      setTimeout(() => {
      feedBackDiv.style.display = "none";
      }, 3000);
      score = score + 5;
      scorePara.textContent = `Score is currently: ${score}`;
      attempts = 5;
      attemptsPara.textContent = `${attempts} attempts remaining`;
      input.value = "";
      newReq(); //call function to load and display new character
      } else {
      feedBackText.textContent = `${input.value} is wrong`;
      feedBackDiv.append(feedBackText);
      feedBackDiv.style.backgroundColor = "red";
      feedBackDiv.style.display = "block";
      input.focus();
      setTimeout(() => {
      feedBackDiv.style.display = "none";
      }, 2000);
      attempts = attempts - 1;
      attemptsPara.textContent = `${attempts} attempts remaining`;

      if (attempts <= 0) {
      answerBtn.disabled = true;
      attemptsPara.textContent = `Game over bro!`;
      }
      }
      console.log(attempts); //check how many attempts remaining every time answerBtn is clicked
      });
      };

      newCharacterBtn.addEventListener("click", newReq);

      //function to make a new request and display it the information on the DOM,when New character button is clicked
      function newReq() {
      rand = randomNumber = Math.round(Math.random() * 100 + 2);
      var request = new XMLHttpRequest();
      request.open(
      "GET",
      "https://kitsu.io/api/edge/characters/" + randomNumber,
      true
      );

      request.send();

      request.onload = function() {
      var data = JSON.parse(this.response);
      var info = data.data;
      displayCharacters(info);

      answerBtn.addEventListener("click", () => {
      let englishName = info.attributes.name;
      if (input.value === englishName) {
      feedBackText.textContent = `${input.value} is correct`;
      feedBackDiv.append(feedBackText);
      feedBackDiv.style.backgroundColor = "green";
      feedBackDiv.style.display = "block";
      //settimeout to hide feedBack div
      setTimeout(() => {
      feedBackDiv.style.display = "none";
      }, 3000);
      score = score + 5;
      scorePara.textContent = `Score is currently: ${score}`;
      attempts = 5;
      attemptsPara.textContent = `${attempts} attempts remaining`;
      input.value = "";
      newReq();
      } else if (input.value != englishName) {
      feedBackText.textContent = `${input.value} is wrong`;
      feedBackDiv.append(feedBackText);
      feedBackDiv.style.backgroundColor = "red";
      feedBackDiv.style.display = "block";
      input.focus();
      //settimeout to hide feedBack div
      setTimeout(() => {
      feedBackDiv.style.display = "none";
      }, 2000);
      attempts = attempts - 1;
      attemptsPara.textContent = `${attempts} attempts remaining`;

      if (attempts <= 0) {
      answerBtn.disabled = true;
      attemptsPara.textContent = `Game over bro!`;
      }
      }
      });
      console.log(attempts);
      };
      }

      body {
      margin: 0;
      padding: 0;
      background: black;
      }

      #imageHolder {
      height: 560px;
      width: 1100px;
      background: #098;
      margin: 10px auto;
      }

      #buttonHolder {
      /* background: #453; */
      width: 160px;
      margin: 0 auto;
      }

      p,
      h3 {
      color: yellowgreen;
      text-align: center;
      }

      h3 {
      text-decoration: underline;
      }

      img {
      width: 100%;
      height: 100%;
      }

      button,
      input {
      margin: 10px 10px;
      border: none;
      background: #098;
      display: block;
      }

      input {
      background: white;
      }


      /* for the question and awnswer game */

      #feedBack {
      background: #098;
      height: 120px;
      width: 320px;
      margin: 10px auto;
      display: none;
      }

      <p id="score"></p>

      <p id="character"></p>

      <input type="text"> <button id="answer">Answer</button> <button id="newCharacter">New Character</button>

      <p id="attempts"></p>

      <div id="feedBack">

      </div>





      var attemptsPara = document.querySelector("#attempts"),
      attempts = 5,
      scorePara = document.querySelector("#score"),
      score = 0,
      feedBackDiv = document.querySelector("#feedBack"),
      newCharacterBtn = document.querySelector("#newCharacter"),
      answerBtn = document.querySelector("#answer"),
      input = document.querySelector("input");

      scorePara.textContent = `Score is currently: ${score}`;
      attemptsPara.textContent = `${attempts} attempts remaining`;

      var feedBackText = document.createElement("p");

      var characterPara = document.querySelector("#character");

      //click new character button to load new character
      // newCharacterBtn.addEventListener("click", () => {
      // answerBtn.disabled = false;
      // attempts = 5;
      // attemptsPara.textContent = `${attempts} attempts remaining`;
      // });

      //function that displays retrieved data to the DOM
      function displayCharacters(info) {
      let englishName = info.attributes.name;
      characterPara.textContent = `This is the character's name: ${englishName}`;
      console.log(englishName, randomNumber);
      }


      //load new character
      var randomNumber = Math.round(Math.random() * 100 + 2);
      var request = new XMLHttpRequest();
      request.open(
      "GET",
      "https://kitsu.io/api/edge/characters/" + randomNumber,
      true
      );

      request.send();

      request.onload = function() {
      var data = JSON.parse(this.response);
      var info = data.data;
      displayCharacters(info);

      //checks if the input value matches name retrieved
      answerBtn.addEventListener("click", () => {
      let englishName = info.attributes.name;
      if (input.value === englishName) {
      feedBackText.textContent = `${input.value} is correct`;
      feedBackDiv.append(feedBackText);
      feedBackDiv.style.backgroundColor = "green";
      feedBackDiv.style.display = "block";
      setTimeout(() => {
      feedBackDiv.style.display = "none";
      }, 3000);
      score = score + 5;
      scorePara.textContent = `Score is currently: ${score}`;
      attempts = 5;
      attemptsPara.textContent = `${attempts} attempts remaining`;
      input.value = "";
      newReq(); //call function to load and display new character
      } else {
      feedBackText.textContent = `${input.value} is wrong`;
      feedBackDiv.append(feedBackText);
      feedBackDiv.style.backgroundColor = "red";
      feedBackDiv.style.display = "block";
      input.focus();
      setTimeout(() => {
      feedBackDiv.style.display = "none";
      }, 2000);
      attempts = attempts - 1;
      attemptsPara.textContent = `${attempts} attempts remaining`;

      if (attempts <= 0) {
      answerBtn.disabled = true;
      attemptsPara.textContent = `Game over bro!`;
      }
      }
      console.log(attempts); //check how many attempts remaining every time answerBtn is clicked
      });
      };

      newCharacterBtn.addEventListener("click", newReq);

      //function to make a new request and display it the information on the DOM,when New character button is clicked
      function newReq() {
      rand = randomNumber = Math.round(Math.random() * 100 + 2);
      var request = new XMLHttpRequest();
      request.open(
      "GET",
      "https://kitsu.io/api/edge/characters/" + randomNumber,
      true
      );

      request.send();

      request.onload = function() {
      var data = JSON.parse(this.response);
      var info = data.data;
      displayCharacters(info);

      answerBtn.addEventListener("click", () => {
      let englishName = info.attributes.name;
      if (input.value === englishName) {
      feedBackText.textContent = `${input.value} is correct`;
      feedBackDiv.append(feedBackText);
      feedBackDiv.style.backgroundColor = "green";
      feedBackDiv.style.display = "block";
      //settimeout to hide feedBack div
      setTimeout(() => {
      feedBackDiv.style.display = "none";
      }, 3000);
      score = score + 5;
      scorePara.textContent = `Score is currently: ${score}`;
      attempts = 5;
      attemptsPara.textContent = `${attempts} attempts remaining`;
      input.value = "";
      newReq();
      } else if (input.value != englishName) {
      feedBackText.textContent = `${input.value} is wrong`;
      feedBackDiv.append(feedBackText);
      feedBackDiv.style.backgroundColor = "red";
      feedBackDiv.style.display = "block";
      input.focus();
      //settimeout to hide feedBack div
      setTimeout(() => {
      feedBackDiv.style.display = "none";
      }, 2000);
      attempts = attempts - 1;
      attemptsPara.textContent = `${attempts} attempts remaining`;

      if (attempts <= 0) {
      answerBtn.disabled = true;
      attemptsPara.textContent = `Game over bro!`;
      }
      }
      });
      console.log(attempts);
      };
      }

      body {
      margin: 0;
      padding: 0;
      background: black;
      }

      #imageHolder {
      height: 560px;
      width: 1100px;
      background: #098;
      margin: 10px auto;
      }

      #buttonHolder {
      /* background: #453; */
      width: 160px;
      margin: 0 auto;
      }

      p,
      h3 {
      color: yellowgreen;
      text-align: center;
      }

      h3 {
      text-decoration: underline;
      }

      img {
      width: 100%;
      height: 100%;
      }

      button,
      input {
      margin: 10px 10px;
      border: none;
      background: #098;
      display: block;
      }

      input {
      background: white;
      }


      /* for the question and awnswer game */

      #feedBack {
      background: #098;
      height: 120px;
      width: 320px;
      margin: 10px auto;
      display: none;
      }

      <p id="score"></p>

      <p id="character"></p>

      <input type="text"> <button id="answer">Answer</button> <button id="newCharacter">New Character</button>

      <p id="attempts"></p>

      <div id="feedBack">

      </div>






      javascript html performance variables






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 25 '18 at 11:19









      KingRogueKingRogue

      135




      135
























          1 Answer
          1






          active

          oldest

          votes


















          0














          Your problem arises from calling answerBtn.addEventListener every time the answer returns - which adds more and more listeners.



          Add a console log at the beginning of the click event and you'll see that after the 2nd answer the click event happens twice, then three times on the 3rd answer, etc'.
          This means that on the first click the result is correct, but then on the rest of the clicks it is incorrect and must be causing the bug.



          You should only listen to the event once, the variables that the event uses change and that should be sufficient. I can't fix the code for you at this time, apologies.






          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53466918%2fvariable-tracking-user-attempts-does-not-update%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            Your problem arises from calling answerBtn.addEventListener every time the answer returns - which adds more and more listeners.



            Add a console log at the beginning of the click event and you'll see that after the 2nd answer the click event happens twice, then three times on the 3rd answer, etc'.
            This means that on the first click the result is correct, but then on the rest of the clicks it is incorrect and must be causing the bug.



            You should only listen to the event once, the variables that the event uses change and that should be sufficient. I can't fix the code for you at this time, apologies.






            share|improve this answer




























              0














              Your problem arises from calling answerBtn.addEventListener every time the answer returns - which adds more and more listeners.



              Add a console log at the beginning of the click event and you'll see that after the 2nd answer the click event happens twice, then three times on the 3rd answer, etc'.
              This means that on the first click the result is correct, but then on the rest of the clicks it is incorrect and must be causing the bug.



              You should only listen to the event once, the variables that the event uses change and that should be sufficient. I can't fix the code for you at this time, apologies.






              share|improve this answer


























                0












                0








                0







                Your problem arises from calling answerBtn.addEventListener every time the answer returns - which adds more and more listeners.



                Add a console log at the beginning of the click event and you'll see that after the 2nd answer the click event happens twice, then three times on the 3rd answer, etc'.
                This means that on the first click the result is correct, but then on the rest of the clicks it is incorrect and must be causing the bug.



                You should only listen to the event once, the variables that the event uses change and that should be sufficient. I can't fix the code for you at this time, apologies.






                share|improve this answer













                Your problem arises from calling answerBtn.addEventListener every time the answer returns - which adds more and more listeners.



                Add a console log at the beginning of the click event and you'll see that after the 2nd answer the click event happens twice, then three times on the 3rd answer, etc'.
                This means that on the first click the result is correct, but then on the rest of the clicks it is incorrect and must be causing the bug.



                You should only listen to the event once, the variables that the event uses change and that should be sufficient. I can't fix the code for you at this time, apologies.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 25 '18 at 12:59









                ShushanShushan

                1,1171815




                1,1171815
































                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53466918%2fvariable-tracking-user-attempts-does-not-update%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Tonle Sap (See)

                    I get strange results when I access the Sqlitedatabase with Unity C# via XAMPP

                    Guatemaltekische Davis-Cup-Mannschaft