patternjavascriptMinor
Static quiz module with predefined answers
Viewed 0 times
predefinedwithanswersquizmodulestatic
Problem
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:
HTML:
```
Writing Object Oriented JavaScript is no
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:
```
Writing Object Oriented JavaScript is no
Solution
Overall this is already pretty well organized and compact. There isn't a lot of duplication or obvious abstractions that can be made. It would be helpful to see the HTML to see if there are any changes that would make the Javascript easier to write.
A couple of suggestions:
-
Wrap the entire code block in an IIFE to avoid cluttering global namespace
-
Use
-
Some of your variables are only being referenced once and can be inlined:
A couple of suggestions:
-
Wrap the entire code block in an IIFE to avoid cluttering global namespace
(function ($, undefined) {
// Your code here ...
} (jQuery));-
Use
.width() instead of .css('width', ...)-
Some of your variables are only being referenced once and can be inlined:
$('.flag').on('click', ...); // etc.Code Snippets
(function ($, undefined) {
// Your code here ...
} (jQuery));$('.flag').on('click', ...); // etc.Context
StackExchange Code Review Q#12164, answer score: 3
Revisions (0)
No revisions yet.