-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
88 lines (76 loc) · 2.51 KB
/
script.js
File metadata and controls
88 lines (76 loc) · 2.51 KB
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
let display = document.querySelector(".display-inp");
let btns = document.querySelectorAll("input[type=button]");
let click = new Audio('audio/click.wav')
let clear = new Audio('audio/AC.wav')
let del = new Audio('audio/del.wav')
let errorS = new Audio('audio/error.mp3')
btns.forEach((button) => {
button.addEventListener("click", function () {
let value = this.value;
if (value === "=" && display.value === ""){
errorS.play();
return;
}
if (value === "=") {
del.play()
try {
let equation = display.value;
let result = eval(equation);
display.value = result;
} catch (error) {
display.value = "Error";
}
} else if (value === "AC") {
del.play()
display.value = "";
} else if (value === "DE") {
del.play()
display.value = display.value.toString().slice(0, -1);
} else {
if (display.value === "Error") {
display.value = "";
}
click.play();
display.value += value;
}
if (display.value === "Error")
errorS.play();
// Automatically scroll to the bottom
display.scrollTop = display.scrollHeight;
});
});
document.addEventListener("keydown", (event) => {
let key = event.key;
// Ensure `display` and sounds exist
if (!display || !click || !del || !errorS || !clear) return;
if (key >= "0" && key <= "9") {
click.play();
if (display.value === "Error") display.value = ""; // Reset if error
display.value += key;
}
if (["+", "/", "-", "*","^"].includes(key)) {
click.play();
if (display.value === "Error") display.value = ""; // Reset if error
display.value += key;
}
if (key === "Enter" && display.value !== "") {
del.play();
try {
let equation = display.value;
// Evaluate the expression safely
let result = eval(equation);
display.value = result;
} catch (error) {
display.value = "Error";
errorS.play();
}
}
if (key === "Backspace") {
del.play();
display.value = display.value.toString().slice(0, -1);
}
if (key === "Delete") {
clear.play();
display.value = "";
}
});