Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
93 lines (79 loc) · 2.04 KB
/
Copy pathscript.js
File metadata and controls
93 lines (79 loc) · 2.04 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
89
90
91
92
93
const display = document.getElementById('display');
// Append numbers/operators to the screen
function appendValue(value) {
if (display.value === '0' || display.value === 'Error') {
display.value = value;
} else {
display.value += value;
}
}
// Clear screen back to 0
function clearDisplay() {
display.value = '0';
}
// Remove the last character entered
function deleteLast() {
if (display.value.length === 1 || display.value === 'Error') {
display.value = '0';
} else {
display.value = display.value.slice(0, -1);
}
}
// Evaluate string calculation using Function constructor (safer alternative to eval)
function calculate() {
try {
display.value = new Function(`return ${display.value}`)();
} catch (error) {
display.value = 'Error';
}
}
// 1. Existing calculator functions from before
function appendValue(value) {
if (display.value === '0' || display.value === 'Error') {
display.value = value;
} else {
display.value += value;
}
}
function clearDisplay() {
display.value = '0';
}
function deleteLast() {
if (display.value.length === 1 || display.value === 'Error') {
display.value = '0';
} else {
display.value = display.value.slice(0, -1);
}
}
function calculate() {
try {
display.value = new Function(`return ${display.value}`)();
} catch (error) {
display.value = 'Error';
}
}
// 2. NEW: Listen for physical keyboard events
window.addEventListener('keydown', (event) => {
const key = event.key;
// Numbers (0-9) and Decimal (.)
if ((key >= '0' && key <= '9') || key === '.') {
appendValue(key);
}
// Operators (+, -, *, /)
if (['+', '-', '*', '/'].includes(key)) {
appendValue(key);
}
// Equals (Enter or '=')
if (key === 'Enter' || key === '=') {
event.preventDefault(); // Prevents default form submission if wrapped in a form
calculate();
}
// Delete / Backspace
if (key === 'Backspace') {
deleteLast();
}
// Clear (Escape key or 'c' / 'C')
if (key === 'Escape' || key.toLowerCase() === 'c') {
clearDisplay();
}
});