-
Notifications
You must be signed in to change notification settings - Fork 0
/
CalculatorConfig.js
42 lines (37 loc) · 1.81 KB
/
CalculatorConfig.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
function setup() {
window.onload = () => {
for (let i = 0; i < 10; i++) {
document.getElementById(i.toString()).addEventListener("click", () => {
document.getElementById("equation").innerText += i.toString();
});
}
// Operator Button Listeners
document.getElementById("+").addEventListener("click", () => {operatorListeners("+")})
document.getElementById("-").addEventListener("click", () => {operatorListeners("-")})
document.getElementById("/").addEventListener("click", () => {operatorListeners("÷")})
document.getElementById("x").addEventListener("click", () => {operatorListeners("×")})
document.getElementById("C").addEventListener("click", () => {
document.getElementById("equation").innerText = "";
document.getElementById("result").innerText = "";
});
document.getElementById("=").addEventListener("click", () => {
if (document.getElementById("equation").innerText !== "") {
let formattedEquation = document.getElementById("equation").innerText.replaceAll("×", "*").replaceAll("÷", "/");
try {
document.getElementById("result").innerText = "=" + eval(formattedEquation).toString();
}
catch (e) {
document.getElementById("result").innerText = "ERROR";
}
}
});
}
}
function operatorListeners(operator) {
let equation = document.getElementById("equation").innerText;
let i = equation.length - 1;
if (equation !== "" && equation.charAt(i) !== "+" && equation.charAt(i) !== "-" && equation.charAt(i) !== "×" && equation.charAt(i) !== "÷") {
document.getElementById("equation").innerText += operator;
}
}
setup();