-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
107 lines (87 loc) · 2.59 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
107
function add(a, b) {
return Number(a) + Number(b);
}
function subtract(a, b) {
return Number(a) - Number(b);
}
function multiply(a, b) {
return Number(a) * Number(b);
}
function divide(a, b) {
if (b == 0) {
return "Can't Divide by Zero";
}
return Number(a) / Number(b);
}
function operate(operator, a, b) {
if (operator === "+") {
return add(a, b);
}
if (operator === "-") {
return subtract(a, b);
}
if (operator === "x") {
return multiply(a, b);
}
if (operator === "/") {
return divide(a, b);
}
}
function firstOrSecondNum(e) {
if (!operatorOnCalc) {
firstNum += `${e.target.textContent}`;
document.querySelector(".screen").textContent = `${firstNum}`;
} else if (firstNum && operatorOnCalc) {
const clearScreen = document.querySelector(".screen");
clearScreen.textContent = "";
secondNum += `${e.target.textContent}`;
document.querySelector(".screen").textContent = `${secondNum}`;
} else {
secondNum += `${e.target.textContent}`;
document.querySelector(".screen").textContent = `${secondNum}`;
}
}
let firstNum = "";
let secondNum = "";
let operatorOnCalc = "";
// Add click listeners
const numberButtons = document.querySelectorAll(".number");
const operatorButtons = document.querySelectorAll(".operator");
const equalButton = document.querySelector(".equal");
const clearButton = document.querySelector(".clear");
const backspaceButton = document.querySelector(".backspace");
for (const button of numberButtons) {
button.addEventListener("click", firstOrSecondNum);
}
for (const button of operatorButtons) {
button.addEventListener("click", (e) => {
if (firstNum) {
operatorOnCalc = `${e.target.textContent}`;
}
});
}
equalButton.addEventListener("click", () => {
if (!operatorOnCalc) {
return document.querySelector(".screen").textContent;
}
if (secondNum) {
const answer = operate(operatorOnCalc, firstNum, secondNum);
document.querySelector(".screen").textContent = `${answer}`;
firstNum = answer;
secondNum = "";
operatorOnCalc = "";
}
});
clearButton.addEventListener("click", () => {
document.querySelector(".screen").textContent = "";
firstNum = "";
secondNum = "";
});
backspaceButton.addEventListener("click", () => {
let screen = document.querySelector(".screen").textContent;
let numberBackspace = screen.split("").slice(0, -1);
document.querySelector(".screen").textContent = `${numberBackspace.join("")}`;
operatorOnCalc
? (secondNum = document.querySelector(".screen").textContent)
: (firstNum = document.querySelector(".screen").textContent);
});