MathQuiz
HTML
<form id=form action=post>
<div id=equation>
<div id=a>0</div>
<div id=op>%</div>
<div id=b>0</div>
</div>
<input id=ans autofocus required autocomplete="off" />
</form>
<script>MathQuiz.dom.example();</script>
CSS
#equation {
margin:auto;
width:2em;
border-bottom:3px solid black;
}
#op {
float:left;
}
#a, #b {
width:2em;
text-align:right;
}
#form {
font-size:4em;
width:3em;
padding:0.5em 0 0.5em 0;
margin:auto;
border:1px solid black;
text-align:center;
}
#ans {
width:2em;
font-size:inherit;
border:0px;
text-align:right;
font-family:inherit;
}
JavaScript
"use strict";
Math.add = (Math.add ||
function(a, b) {
return (+a) + (+b);
});
Math.subtract = (Math.subtract ||
function(a, b) {
return a - b;
});
Math.random.number = (Math.random.number ||
function(min, max) {
return Math.random() * (max - min) + min;
});
Math.random.int = (Math.random.int ||
function(min, max) {
return Math.floor(Math.random.number(min, max));
});
Math.random.key = (Math.random.key ||
function(obj) {
var k, r, i = 0;
for (k in obj) {
if (obj.hasOwnProperty(k) && Math.random() < 1 / ++i) {
r = k;
}
}
return r;
});
var MathQuiz = function(obj) {
this.generate = function() {
obj.a[obj.aKey] = Math.random.int(obj.min, obj.max);
obj.b[obj.bKey] = Math.random.int(obj.min, obj.max);
obj.op[obj.opKey] = Math.random.key(obj.fn);
};
this.answer = function() {
var a = obj.a[obj.aKey],
b = obj.b[obj.bKey],
fn = obj.fn[obj.op[obj.opKey]];
return fn(a, b);
};
this.test = function() {
var ans = obj.ans[obj.ansKey];
return ans == this.answer();
};
};
MathQuiz.addition = {
'+': Math.add
};
MathQuiz.subtraction = {
'-': Math.subtract
};
MathQuiz.additionAndSubtraction = {
'+': Math.add,
'-': Math.subtract
};
MathQuiz.dom = {};
MathQuiz.dom.example = function() {
function id(ID) {
return document.getElementById(ID);
}
var h = 'innerHTML',
mq = new MathQuiz({
a: id('a'),
aKey: h,
b: id('b'),
bKey: h,
op: id('op'),
opKey: h,
ans: id('ans'),
ansKey: 'value',
fn: MathQuiz.additionAndSubtraction,
min: 1,
max: 10
});
function init() {
mq.generate();
var ans = id('ans');
ans.pattern = mq.answer();
ans.value = "";
}
function f() {
if(mq.test()) {
alert("Good...