This is jQuery code which works like this: depending on a user choice it changes the color and background of some elements in the DOM.
The behavior is ok, is doing exactly what I want.
And as you may see, there is some code repeated. What's the best way to keep a good performance by doing a function in order to avoid repeating code?
function ArticleQuiz($el){
this.$el = $el;
this.answer = this.$el.data('answer');
this.answerContainer = this.$el.find('.answer-container');
this.result = this.$el.find('.result');
this.correctAnswer = this.$el.find('.correct-answer');
this.incorrectAnswer = this.$el.find('.incorrect-answer');
this.quizLogic();
return this;
}
ArticleQuiz.prototype.quizLogic = function(){
var THIS = this;
var answer;
$('.masthead-article-quiz').parent().css('background', '#eee');
$('.quiz-cols a', this.$el).click(function(e) {
THIS.target = $(e.target);
e.preventDefault();
// exit if choice already made: users can't change their pick
if ($(this).parents('.quiz-cols').parent().find('.white-font').length) return;
// set class according to data-answer:
if (THIS.target.hasClass('icon-false-shape')) {
THIS.answerContainer.show();
$(this).addClass('background-' + ((THIS.answer === false) ? 'green' : 'red')).addClass('white-font');
THIS.result.addClass('font-' + ((THIS.answer === false) ? 'green' : 'red'));
answer = THIS.answer ? THIS.incorrectAnswer.show() : THIS.correctAnswer.show();
}
if (THIS.target.hasClass('icon-true-shape')) {
THIS.answerContainer.show();
$(this).addClass('background-' + ((THIS.answer === true) ? 'green' : 'red')).addClass('white-font');
THIS.result.addClass('font-' + ((THIS.answer === true) ? 'green' : 'red'));
answer = !THIS.answer ? THIS.incorrectAnswer.show() : THIS.correctAnswer.show();
}
});
return THIS;
};
correctAnswer
andincorrectAnswer
defined? \$\endgroup\$ – Mike Brant Dec 12 '16 at 16:58