-
Notifications
You must be signed in to change notification settings - Fork 0
/
math.js
68 lines (61 loc) · 1.96 KB
/
math.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// global variables
const operators = ["+", "-", "*", "/"];
let number1, number2, operator;
let score = 0;
// start function
function start() {
number1 = Math.floor(Math.random() * 50) + 1;
number2 = Math.floor(Math.random() * 20) + 1;
operator = operators[Math.floor(Math.random() * operators.length)];
document.getElementById("number1").innerHTML = number1;
document.getElementById("number2").innerHTML = number2;
document.getElementById("operator").innerHTML = operator;
document.getElementById("reset").style.visibility = "hidden";
document.getElementById("score").innerHTML = score;
reset();
}
// resetting the input and error message
function reset() {
document.getElementById("answer").focus();
document.getElementById("answer").value = "";
// document.getElementById("result").innerHTML = "";
return true;
}
// check answer
function checkAnswer() {
const answer = document.getElementById("answer").value;
document.getElementById("reset").style.visibility = "hidden";
if (answer !== "") {
let message = "";
const equation = eval(number1 + operator + number2);
if (equation == answer) {
score += 10;
message = "<span class='green'>" + answer + " is correct!</span>";
start();
} else {
document.getElementById("reset").style.visibility = "visible";
if (isNaN(answer)) {
message =
"<span class='maroon'>Hey! " +
answer +
" is not a valid number!</span>";
} else {
score -= 10;
message = "<span class='red'>" + answer + " is incorrect!</span>";
}
reset();
}
// display answer
document.getElementById("result").innerHTML = message;
document.getElementById("score").innerHTML = score;
}
return true;
}
// check for answer when enter is pressed
document.getElementById("answer").addEventListener("keyup", function(e) {
// 13 is for enter key
if (e.which === 13 || e.keyCode === 13) {
checkAnswer();
}
return false;
});