-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
38 lines (34 loc) · 965 Bytes
/
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
const screen = document.getElementById("calc-screen");
// Function for Calculator Input Screen
function updateScreen(value) {
if (value === "C") {
screen.value = "";
} else if (value === "=") {
try {
screen.value = eval(screen.value);
} catch {
screen.value = "Error";
}
} else {
screen.value += value;
}
}
// Event Listener for Button Clicks
document.querySelectorAll("button").forEach((button) => {
button.addEventListener("click", () => {
updateScreen(button.value);
});
});
// Event Listener for Keyboard Inputs
document.addEventListener("keydown", (e) => {
const key = e.key;
if (!isNaN(key) || ["+", "-", "*", "/"].includes(key)) {
screen.value += key;
} else if (key === "Enter" || key === "=") {
updateScreen("=");
} else if (key === "Backspace") {
screen.value = screen.value.slice(0, -1);
} else if (key === "Escape" || key === "c" || key === "C") {
updateScreen("C");
}
});