-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
73 lines (66 loc) · 2.16 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
62
63
64
65
66
67
68
69
70
71
72
73
// Select the calculator and display elements
const calculator = document.querySelector('.calculator');
const resultDisplay = document.querySelector('.result');
const operationDisplay = document.querySelector('.operation');
// Track the current input and result
let currentInput = '';
let previousInput = '';
let operator = null;
let resetScreen = false;
// Function to update the display
function updateDisplay() {
operationDisplay.textContent = previousInput + (operator || '') + currentInput;
resultDisplay.textContent = currentInput || '0';
}
// Function to handle calculations
function calculate() {
if (previousInput && currentInput && operator) {
const result = eval(`${previousInput} ${operator} ${currentInput}`);
currentInput = result.toString();
previousInput = '';
operator = null;
resetScreen = true;
}
}
// Handle number and operator buttons
document.querySelectorAll('.button').forEach(button => {
button.addEventListener('click', () => {
const value = button.textContent;
if (/\d/.test(value) || value === '.') {
// Append numbers and decimal to the current input
if (resetScreen) {
currentInput = value;
resetScreen = false;
} else {
currentInput += value;
}
} else if (value === 'AC') {
currentInput = '';
previousInput = '';
operator = null;
} else if (value === '⌫') {
currentInput = currentInput.slice(0, -1);
} else if (value === '=') {
calculate();
} else {
// Handle operator buttons
if (currentInput) {
if (previousInput && operator) {
calculate();
} else {
previousInput = currentInput;
currentInput = '';
}
}
operator = value === '×' ? '*' : value === '−' ? '-' : value;
}
updateDisplay();
});
});
// Toggle between dark and light mode
document.getElementById('toggle-theme').addEventListener('click', () => {
calculator.classList.toggle('light-mode');
calculator.classList.toggle('dark-mode');
const themeIcon = document.getElementById('toggle-theme');
themeIcon.textContent = calculator.classList.contains('light-mode') ? '☀️' : '🌙';
});