<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<button class="test" onClick="test(0)">Take the test</button>
</body>
</html>
var test = (function($test) {
/*jshint validthis: true */
"use strict";
var choices = ["a", "b", "c", "d", "e", "f"];
var warn = "Answer the question!";
var guide = "Type in the letter indicated next to the answer you want to select";
function Tester(config) {
//bind all functions in config obj to constructor context so they access to config properties
for (var p in config) this[p] = typeof config[p] === "function" ? config[p].bind(this) : config[p];
return this;
}
function ask(curr, warning) {
if (warning) alert(warning);
if (curr === $test.length) return alert("score: " + this.score + "/" + $test.length + "\r\r" + "review:" + toJson(this.review));
var question = $test[curr];
var promptDisp = [ guide, "\r\r", (curr + 1), ". ", question.q, "\r", multipleAnswer(question.c, {}) ].join("");
var answer = prompt(promptDisp);
if (!answer || answer === "") return this.ask(curr, warn); //must use this.ask, not ask, since this.ask is a different reference
if (answer.toLowerCase() === question.a) this.score++;
this.review.push({ question: question.q, "your answer": answer, "correct answer": question.a });
if (curr < $test.length) return this.ask(curr + 1);
}
function multipleAnswer(o, tmp) {
o.forEach(function(c, i) {
tmp[choices[i]] = c;
});
return toJson(tmp);
}
function toJson(s) {
return JSON.stringify(s, null, 1).replace(/[\]\[\{\}\,\\"]*/g, "");
}
function init() {
var instance = new Tester({
score: 0,
review: [],
ask: ask
});
instance.ask(0); //instance.ask already bound to instance context
}
return init;
})([
//answer is multiple choice, a, b, c, d, etc.
{
q: "What is 1 + 1?",
a: "c",
c: [45, 3, 2]
},
{
q: "Is the earth flat?",
a: "a",
c: ["no", "yes"]
}
]);
/* Styles go here */
.test {
position:absolute;
left:40%;
top:30%;
font-size:45pt;
font-family:"Helvetica", sans-serif;
cursor:pointer;
border:1px solid #848484;
color:#848484;
padding:50px;
}
.test:hover {
border:1px solid black;
color:black;
}