json based scoring quiz
Using an external data source, load questions, answers and scores to provide an embeddable quiz using jquery.
HTML
<button type="button" id="start">Start</button>
<div id="quiz-content"></div>
CSS
/* example quiz form styles */
#quizForm {
border: 2px dotted;
border-color: #BCBCBC;
background: #F1F1F1;
padding: 20px;
margin: 5px;
}
#quizForm p {
color: #4679BD;
font-size : 1.5em;
}
#quizForm div label {
color: #4F3774;
}
#quizForm button {
background: #fff;
color: #4679BD;
}
JavaScript
$(document).ready(function(){
'use strict';
// GLOBAL:
var $placeHolder = $('#quiz-content'),
loadingGif = 'http://www.ajaxload.info/images/exemples/21.gif',
dataSource = 'https://dl.dropboxusercontent.com/s/4y8ogxu782v64hc/data.json',
currentQuestion = 0,
questionCount = 0,
answerArray = [],
infoMode = false,
gotData = false,
inMemoryData = [];
$("#start").click(function(){
currentQuestion = 0;
questionCount = 0;
answerArray = [];
infoMode = false;
gotData = false;
inMemoryData = [];
quiz().init();
quiz().bindSubmit();
});
// QUIZ LOGIC:
var quiz = function () {
// private methods:
var getQuizData = function (url) {
var promise = $.getJSON(url);
return promise;
};
var getScore = function () {
var score = 0;
$(answerArray).each(function (index, object) {
score += parseInt(object[0].value, 10);
});
return score;
};
var updateScore = function (userAnswer) {
//console.log(userAnswer);
answerArray.push(userAnswer);
};
var getHTML = function (data, currentQuestion) {
console.log("current question: " + currentQuestion + " info mode: " + infoMode);
var content, complete = true;
$(data).each(function (index, object) {
$(object.questions).each(function (index, object) {
if (infoMode) {
if (currentQuestion === index) {
infoMode = false;
complete = false;
content = infoHTML(object.info);
}
} else {
if (currentQuestion === index) {
complete = false;
...