-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
61 lines (56 loc) · 1.79 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
// Get references to the display and buttons
const display = document.getElementById("display");
const buttons = document.querySelectorAll(".button");
// Define the current input and operator
let currentInput = "";
let operator = null;
// Handle button clicks
buttons.forEach(button => {
button.addEventListener("click", function() {
const value = button.dataset.value;
const action = button.dataset.action;
// Handle different button actions
if (action) {
handleAction(action);
} else {
handleInput(value);
}
});
});
// Function to handle input
function handleInput(value) {
if (currentInput === "0" && value !== ".") {
currentInput = value;
} else {
currentInput += value;
}
display.textContent = currentInput;
}
// Function to handle different actions
function handleAction(action) {
if (action === "clear") {
currentInput = "0";
operator = null;
display.textContent = currentInput;
} else if (action === "equals") {
try {
currentInput = eval(currentInput).toString();
display.textContent = currentInput;
} catch {
display.textContent = "Error";
currentInput = "0";
}
} else if (action === "plus-minus") {
if (currentInput) {
if (currentInput.startsWith("-")) {
currentInput = currentInput.slice(1);
} else {
currentInput = "-" + currentInput;
}
display.textContent = currentInput;
}
} else if (action === "percent") {
currentInput = (parseFloat(currentInput) / 100).toString();
display.textContent = currentInput;
}
}