json based scoring quiz
Using an external data source, load questions, answers and scores to provide an embeddable quiz using jquery.
by ian_smithz
HTML
<div class="container">
<br />
<div id="quiz"></div>
</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
/*
Version: 1.2.0
Date: 11/03/2015
Author: Matthew D Webb
Website: http://www.searchlaboratory.com/
Description: json quiz score calculator
Dependencies: JQuery 2.1.0 (cdn here: https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js)
Demo: https://jsfiddle.net/Webby2014/t4p8x02b/
*/
(function ($, undefined) {
'use strict';
// GLOBAL:
var $placeHolder = $('#quiz'),
loadingGif = 'https://dl.dropboxusercontent.com/s/1kzkmwxc978miso/loading.gif',
dataSource = 'https://dl.dropboxusercontent.com/s/4y8ogxu782v64hc/data.json',
currentQuestion = 0,
questionCount = 0,
answerArray = [],
infoMode = false,
gotData = false,
inMemoryData = {};
// QUIZ LOGIC:
var quiz = function () {
// private methods:
var getQuizData = function (url) {
var promise = $.getJSON(url);
return promise;
};
var getScore = function () {
var score = 0;
console.log(answerArray.length);
$(answerArray).each(function (index, object) {
score += parseInt(object[0].value, 10);
});
return score;
};
var updateScore = function (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 = (!object.includeInfo);
complete = false;
content = infoHTML(object.info);
...