-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
62 lines (55 loc) · 1.6 KB
/
index.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
function numButtonPressed(num) {
const screenDiv = document.getElementById("screen");
if (screenDiv.innerHTML.includes("h1")) {
screenDiv.innerHTML = num;
} else {
screenDiv.innerHTML = screenDiv.innerHTML + num;
}
}
function equalButtonPressed() {
const screenDiv = document.getElementById("screen");
try {
const result = eval(screenDiv.innerHTML);
screenDiv.innerHTML = result;
} catch (error) {
console.error(error);
const screenBeforeError = screenDiv.innerHTML;
screenDiv.innerHTML = "ERROR";
setTimeout(function () {
screenDiv.innerHTML = screenBeforeError;
}, 3000);
}
}
function clearButtonPressed() {
const screenDiv = document.getElementById("screen");
if (screenDiv.innerHTML.length === 1) {
screenDiv.innerHTML = 0;
} else {
screenDiv.innerHTML = screenDiv.innerHTML.slice(
0,
screenDiv.innerHTML.length - 1
);
}
}
function plusMinusButtonPressed() {
const screenDiv = document.getElementById("screen");
const currentResult = eval(screenDiv.innerHTML);
screenDiv.innerHTML = currentResult * -1;
}
function percentButtonPressed() {
const screenDiv = document.getElementById("screen");
const currentResult = eval(screenDiv.innerHTML);
screenDiv.innerHTML = currentResult / 100;
}
document.addEventListener("keydown", (event) => {
if (event.key === "Enter") {
equalButtonPressed();
}
if (event.key === "Backspace") {
clearButtonPressed();
}
const operatorSymbols = ["/", "*", "+", "-", "."];
if (!isNaN(event.key) || operatorSymbols.includes(event.key)) {
numButtonPressed(event.key);
}
});