-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
92 lines (76 loc) · 2.14 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
function add(a, b){
return a + b;
}
function sub(a, b){
return a - b;
}
function mult(a, b){
return a*b;
}
function div(a, b){
return a/b;
}
let num1;
let num2;
let op;
let lastOperand = '';
const operators = ['+', '-', '*', '/'];
function operate(num1, num2, op) {
const operations = {
'+': add,
'-': sub,
'*': mult,
'/': div
};
const operation = operations[op](num1, num2);
return operation;
}
const buttons = document.querySelectorAll('button');
buttons.forEach((button) => {
button.addEventListener('click', () => {
if (button.id != 'equal' && document.getElementById("display").innerHTML != 'Error: Division by zero'){
document.getElementById("display").innerHTML += button.id;
}
if (!isNaN(button.id) || button.id === '.') {
lastOperand += button.id;
if (op) {
num2 = +lastOperand;
} else {
num1 = +lastOperand;
}
} else if (operators.includes(button.id)) {
if (num1 && num2) {
num1 = operate(num1, num2, op);
num2 = '';
}
op = button.id;
lastOperand = '';
} else if (num1 && typeof num2 === 'number' && button.id === 'equal') {
if (op === '/' && num2 === 0){
document.getElementById("display").innerHTML = 'Error: Division by zero';
} else {
document.getElementById("display").innerHTML = Number(operate(num1, num2, op).toFixed(10));
}
} else if (button.id === 'clear') {
document.getElementById("display").innerHTML = '';
num1 = '';
num2 = '';
op = '';
lastOperand = '';
}
button.classList.add('clicked');
setTimeout(() => {
button.classList.remove('clicked');
}, 200);
});
button.addEventListener('mouseover', () => {
if (button.id === 'del' || button.id === 'clear'){
button.style.backgroundColor = '#fd5c63';
} else {
button.style.backgroundColor = 'lightgreen';
}
});
button.addEventListener('mouseleave', () => {
button.style.backgroundColor = 'silver';
});
});