Skip to content

Instantly share code, notes, and snippets.

@1995eaton
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 1995eaton/338618e38db646f1bef0 to your computer and use it in GitHub Desktop.
Save 1995eaton/338618e38db646f1bef0 to your computer and use it in GitHub Desktop.
// Important updates:
// #6 - load function works as intended
// #8 - core functionality works with loading questions and calculating scores
// #9 - completion of task
var Quiz = {
questions: [
{title: "How many hairs are on a pony?", choices: ["0", "1", "2", "More than two"], correctAnswer: 3},
{title: "Who lives in the Barbie Dream House?", choices: ["Barbie & Ken", "Peter & Mary", "Ben & Jerry", "It is an empty house"], correctAnswer: 0}
],
init: function() {
this.button = document.getElementById("btn-next");
this.button.addEventListener("click", this.onButtonClick.bind(this), false);
this.radios = document.querySelectorAll("input[type='radio']");
this.h2 = document.querySelector("h2");
this.form = document.getElementById("myForm");
this.labels = document.getElementsByTagName("label");
this.score = 0;
this.questionNumber = 0;
this.nextQuestion();
},
nextQuestion: function() {
var question = this.questions[this.questionNumber];
if (this.h2.firstChild) {
this.h2.firstChild.data = question.title;
} else {
this.h2.appendChild(document.createTextNode(question.title));
}
for (var i = 0, l = question.choices.length; i < l; i++) {
this.form.elements[i].setAttribute("name", "question");
this.form.elements[i].value = question.choices[i];
this.labels[i].htmlFor = question.choices[i];
if (this.labels[i].firstChild) {
this.labels[i].firstChild.data = question.choices[i];
} else {
this.labels[i].appendChild(document.createTextNode(question.choices[i]));
}
}
},
displayScore: function() {
var container = document.querySelector(".container");
container.removeChild(this.button);
container.removeChild(this.form);
var h1 = document.createElement("h1");
h1.textContent = "Your score is: " + this.score.toString();
container.appendChild(h1);
},
onButtonClick: function(e){
for (var i = 0, l = this.radios.length; i < l; i++) {
if (this.radios[i].checked) {
this.score += +(i === this.questions[this.questionNumber].correctAnswer) * 10;
this.radios[i].checked = false;
break;
}
}
if (++this.questionNumber === this.questions.length) {
this.displayScore();
} else {
this.nextQuestion();
}
return false;
}
};
document.addEventListener("DOMContentLoaded", function() {
Quiz.init();
}, false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment