If you want to achieve this, the first step is to establish your final results and assign them a score of 0
.
var results = [
{points: 0, name: 'red'},
{points: 0, name: 'green'},
/* ... */
];
You also need to define your questions:
var questions = [
{
question : 'Which flower do you like the most?',
answers : [
{ text: 'poppy', result: 0 },
{ text: 'corn-flower', result: 2 },
{ text: 'sunflower', result: 3 },
{ text: 'artichoke', result: 1 }
]
},
/* ... */
];
To accomplish this task, you'll require a few functions along with some variables:
var qEl = document.getElementById('question'),
aEl = document.getElementsByClassName('answer'),
res = document.getElementById('result'),
cur = -1,
question;
// function to display the next question
function nextQuestion(){
cur++;
question = questions[cur];
qEl.innerHTML = (cur+1) + ' - ' + question.question;
for(var i=0; i<aEl.length; i++){
aEl[i].innerHTML = question.answers[i].text;
}
}
// increments the related result by 1 and moves to the next question
function answer(num){
var result = results[question.answers[num].result];
result.points = result.points + 1;
if(cur>=questions.length-1){
for(var i=0, len=aEl.length; i<len; i++){
aEl[i].style.display = 'none';
}
qEl.style.display = 'none';
res.style.display = 'block';
res.innerHTML = 'Your favorite color appears to be ' + getMaxScore() + '!';
res.className = getMaxScore();
} else {
nextQuestion();
}
}
// retrieves the name of the result with the highest score
function getMaxScore(){
var maxPoints = 0;
var maxName = '';
for(var i=0, len=results.length; i<len; i++){
if(results[i].points>maxPoints){
maxPoints = results[i].points;
maxName = results[i].name;
}
}
return maxName;
}
After setting up the functions, you can display the first question and link the answer()
function to the onclick
event of the answer elements.
nextQuestion();
for(var i=0, len=aEl.length; i<len; i++){
(function(index){
aEl[i].onclick = function(){
answer(index);
}
})(i);
}
Lastly, here is the corresponding HTML code:
<h2 id="question"></h2>
<p class="answer"></p>
<p class="answer"></p>
<p class="answer"></p>
<p class="answer"></p>
<h1 id="result"></h1>
Ready to give it a go?