I was building a quiz module for one website. It is a simple true/false statements where you first choose the answer, the correct answer is displayed, and then you can move forward to the next question.
For better understanding, please find working code snippet here.
I need mentor guidance in order to make my existing code shorter and optimized.
Here is the jQuery code for this quiz module:
var flag = $('.quiz ul'),
currentPosition = 0,
currentQuestion = 0,
slideWidth = 200,
option = $('.flag'),
tryCTA = $('.CTAtry'),
nextQuestion = $('.next'),
answer = $('span.answer')
questionWrapper = $('.quiz ul'),
totalQuestions = $('.quiz ul li').length,
answers = ["True","False","False"];
//Set UL width
questionWrapper.css('width',totalQuestions*slideWidth)
option.on('click',function(e) {
e.preventDefault();
var nextCTA = $(this).parent().next(nextQuestion).length,
optionWrapper = $(this).parent();
if(nextCTA) {
optionWrapper.next(nextQuestion).show();
} else {
tryCTA.show();
}
optionWrapper.parent().find(answer).html(answers[currentQuestion]).show();
optionWrapper.hide();
});
nextQuestion.on('click',function(e){
e.preventDefault();
currentPosition = currentPosition+1;
$(this).parent().parent().animate({
'marginLeft' : slideWidth*(-currentPosition)
});
currentQuestion++;
});
tryCTA.on('click',function(e) {
e.preventDefault();
resetQuiz(e);
$(this).hide();
})
function resetQuiz(e) {
$('.quiz ul').animate({
opacity: 0
},0)
.animate({
opacity: 1
},500)
$('span.answer').html(" ");
$('.quiz ul').css('margin-left','0');
$('.options').show();
$('.next').hide();
currentPosition = 0;
currentQuestion = 0;
}
HTML:
<div class="quiz">
<ul>
<li>
<span class="answer"></span>
<p>Writing Object Oriented JavaScript is not a FUN.</p>
<div class="options">
<a href="" class="flag">True</a>
<span>or</span>
<a href="" class="flag">False</a>
</div>
<a href="" class="next">Next</a>
</li>
<li>
<span class="answer"></span>
<p>Let's give it a try! No harm in learning anything NEW.</p>
<div class="options">
<a href="" class="flag">True</a>
<span>or</span>
<a href="" class="flag">False</a>
</div>
<a href="" class="next">Next</a>
</li>
<li>
<span class="answer"></span>
<p>Some code running !</p>
<div class="options">
<a href="" class="flag">True</a>
<span>or</span>
<a href="" class="flag">False</a>
</div>
</li>
</ul>
<a href="" class="CTAtry">Try Again!</a>
</div>