-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
106 lines (99 loc) · 2.39 KB
/
script.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
function add(a, b) {
return a+b;
}
function subtract(a, b) {
return a-b;
}
function multiply(a, b) {
return a*b;
}
function divide(a, b) {
return a/b;
}
function operate(n1, op, n2) {
switch (op) {
case '+':
return add(n1,n2);
case '-':
return subtract(n1,n2);
case 'X':
return multiply(n1,n2);
case '/':
return divide(n1,n2);
case '%':
return n1 % n2;
}
}
function display(n) {
const d = document.querySelector(".display span");
if (res === true) {
d.innerHTML = '';
res = false;
}
d.innerHTML += n;
}
function clear() {
const d = document.querySelector(".display span");
let ch = d.innerHTML;
if (ch === '') {
return;
}else {
d.innerHTML = ch.substring(0, ch.length-1);
}
}
function clearAll() {
const d = document.querySelector(".display span");
d.innerHTML = '';
num1 = '';
num2 = '';
op = '';
res = false;
}
let num1 = '';
let op = '';
let num2 = '';
let res = false;
// Apply display to numbers
const numArr = document.querySelectorAll(".nums button");
numArr.forEach((e) => e.addEventListener("click", (e) => {
display(e.target.innerHTML);
}));
// Apply clear
const clearBtn = document.querySelector("#clear");
clearBtn.addEventListener("click",clear);
// Apply clearAll
const clearAllBtn = document.querySelector("#clearAll");
clearAllBtn.addEventListener("click",clearAll);
// Apply operators
const operators = document.querySelectorAll(".op");
operators.forEach((e) => e.addEventListener("click", (e) => {
// Calculator Logic
const d = document.querySelector(".display span");
if (num1 === '') {
num1 = parseFloat(d.innerHTML);
d.innerHTML = '';
op = e.target.innerHTML;
res = false;
} else {
num2 = parseFloat(d.innerHTML);
num1 = operate(num1, op, num2);
d.innerHTML = num1;
res = true;
}
op = e.target.innerHTML;
}));
const eq = document.querySelector("#equal");
eq.addEventListener("click", () => {
const d = document.querySelector(".display span");
if (num1 === '') {
d.innerHTML = 0;
} else if (op !== ''){
num2 = parseFloat(d.innerHTML);
num1 = operate(num1, op, num2);
d.innerHTML = num1;
num2 = '';
op = '';
num1 = '';
res = true;
}
})