-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
51 lines (46 loc) · 1.31 KB
/
app.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
var result = 0;
var operation = '';
var displayRefresh = false;
var calcTempResult = function() {
var v = parseFloat(document.getElementsByTagName('input')[0].value);
if (operation === '+') {
result += v;
} else if (operation === '-') {
result -= v;
} else if (operation === 'x' || operation === '*') {
result *= v;
} else if (operation === '÷' || operation === '/') {
result /= v;
} else {
result = v;
}
document.getElementsByTagName('input')[0].value = result;
};
var processKey = function(key) {
if ( /\d/.test(key) || key === '.') {
// If the button is a number
if (displayRefresh) {
document.getElementsByTagName('input')[0].value = key;
displayRefresh = false;
} else {
document.getElementsByTagName('input')[0].value += key;
}
} else if (key === 'C'){
result = 0;
operation = '';
document.getElementsByTagName('input')[0].value = '0';
} else {
calcTempResult();
operation = key;
displayRefresh = true;
}
}
var btns = document.getElementsByClassName("flex-item");
[].forEach.call(btns, function (btn) {
btn.onclick = function() {
processKey(btn.textContent);
};
});
document.getElementsByTagName('body')[0].addEventListener("keypress", function(event) {
processKey(event.key);
});