-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
53 lines (47 loc) · 1.78 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
document.addEventListener("DOMContentLoaded", function () {
const display = document.querySelector('.display');
const calculator = document.querySelector('.calculator');
const buttons = Array.from(document.querySelectorAll('.button'));
buttons.forEach(button => {
button.addEventListener('click', function (event) {
handleButtonClick(event);
shuffleButtons();
});
});
function handleButtonClick(event) {
const value = event.target.textContent;
switch (value) {
case 'C':
display.textContent = '0';
break;
case '=':
try {
display.textContent = eval(display.textContent);
} catch (error) {
display.textContent = 'Error';
}
break;
case '←':
if (display.textContent.length === 1 || (display.textContent.length === 2 && display.textContent.startsWith('-'))) {
display.textContent = '0';
} else {
display.textContent = display.textContent.slice(0, -1);
}
break;
default:
if (display.textContent === '0' || display.textContent === 'Error') {
display.textContent = value;
} else {
display.textContent += value;
}
break;
}
}
function shuffleButtons() {
const shuffledButtons = buttons.sort(() => Math.random() - 0.5);
// Ensure the display stays at the top
calculator.appendChild(display);
// Append the shuffled buttons
shuffledButtons.forEach(button => calculator.appendChild(button));
}
});