-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
70 lines (63 loc) · 2.52 KB
/
Copy pathscript.js
File metadata and controls
70 lines (63 loc) · 2.52 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
// Get references to our DOM elements
const display = document.getElementById('display');
const buttonsContainer = document.querySelector('.buttons');
// Maintain a string variable to track user input
let currentInput = "";
// Attach a single event listener to the container (Event Delegation)
buttonsContainer.addEventListener('click', (event) => {
// Check if the clicked element is actually a button
if (!event.target.classList.contains('btn')) return;
// Extract the internal data value of the button
const value = event.target.getAttribute('data-value');
if (value === "C") {
// Clear everything
currentInput = "";
display.value = "0";
}
else if (value === "DEL") {
// Remove the last character typed
currentInput = currentInput.slice(0, -1);
display.value = currentInput || "0";
}
else if (value === "=") {
// Evaluate the string expression safely
try {
if (currentInput.trim() !== "") {
// Perform math calculation
let result = eval(currentInput);
// Keep decimal points reasonable (e.g., 0.1 + 0.2)
if (result.toString().includes('.')) {
result = parseFloat(result.toFixed(4));
}
display.value = result;
currentInput = result.toString(); // Allow continuous calculations
}
} catch (error) {
display.value = "Error";
currentInput = "";
}
}
else {
// Prevent typing multiple consecutive operators or leading zeros brokenly
currentInput += value;
display.value = currentInput;
}
});
// Listen to physical keyboard presses
document.addEventListener('keydown', (event) => {
const key = event.key;
// Map keyboard keys to calculator actions
if (key >= '0' && key <= '9' || key === '.' || key === '+' || key === '-' || key === '*' || key === '/') {
currentInput += key;
display.value = currentInput;
} else if (key === 'Enter' || key === '=') {
event.preventDefault(); // Stop default browser behaviors
document.querySelector('.btn.equal').click();
} else if (key === 'Backspace') {
currentInput = currentInput.slice(0, -1);
display.value = currentInput || "0";
} else if (key === 'Escape') {
currentInput = "";
display.value = "0";
}
});