I'm doing a quiz. First, the user selects how many questions he wants to answer, and then receives answers to them. After they answered the questions, there is a "Back to Top" button that returns them to where the page loads. All this is done by hiding and displaying divs using javascript.
Questions are stored as objects inside an object. If the user wants to answer 5 questions, 5 random questions will be placed in a new object. This object is used to display a question and see how many correct answers the user receives.
When the user finishes the quiz, he will return to the beginning and start a new quiz in which my problem arose. Var, which contains an object with a selected number of questions, is not replaced by a new object containing new questions. Instead, an entirely new var variable is created with the same name, which gives me a TypeError error message in the console.
I simplified my problem in this JSFiddle. The first set of buttons can be seen when the user selects the number of questions and the second button when they answer.
https://jsfiddle.net/v2488zxx/
var firstDivClick = document.getElementsByClassName("button-1"),
secondDivClick = document.getElementsByClassName("button-2");
for(var i = 0; i < firstDivClick.length; i++) {
firstDivClick[i].addEventListener("click", function() {
var valueAsInt = parseInt(this.textContent),
object,
firstDiv = document.getElementById("first-buttons-wrap"),
secondDiv = document.getElementById("second-buttons-wrap");
if(valueAsInt === 2) {
object = {
one: {
text: "Where is my bed?"
},
two: {
text: "Where does Santa Claus live?"
}
}
}
else if(valueAsInt === 3) {
object = {
one: {
text: "Where is my bed?"
},
two: {
text: "Where does Santa Claus live?"
},
three: {
text: "Where does poo live?",
}
}
}
firstDiv.style.display = "none";
secondDiv.style.display = "block";
for(var i = 0; i < secondDivClick.length; i++) {
secondDivClick[i].addEventListener("click", function() {
if(this.textContent === "abc") {
firstDiv.style.display = "block";
secondDiv.style.display = "none";
}
});
}
});
}
Filip source
share