-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
105 lines (92 loc) · 2.71 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
93
94
95
96
97
98
99
100
101
102
103
104
105
const numbers = document.querySelectorAll(".number")
const operators = document.querySelectorAll(".operator")
const equalSign = document.querySelector(".equal-sign")
const clearBtn = document.querySelector(".all-clear")
const decimal = document.querySelector(".decimal")
const calculatorScreen = document.querySelector(".calculator-screen")
let prevNumber = '';
let operation = '';
let currentNumber = '0';
const updateScreen = (number) => {
calculatorScreen.value = number
}
numbers.forEach((number) => {
number.addEventListener("click", (e) =>{
inputNumber(e.target.value)
updateScreen(currentNumber)
})
})
operators.forEach((operator) =>{
operator.addEventListener("click", (e) => {
inputOperator(e.target.value)
})
})
const inputNumber = (number) => {
if(currentNumber === '0'){
currentNumber = number
}else{
currentNumber += number
}
}
const inputOperator = (operator) =>{
if(operation === ''){
prevNumber = currentNumber
}
operation = operator
currentNumber = '0'
}
const calculate = () => {
let result = ''
switch (operation) {
case "+":
result = parseFloat(prevNumber) + parseFloat(currentNumber)
break;
case "-":
result = parseFloat(prevNumber) - parseFloat(currentNumber)
break;
case "*":
result = parseFloat(prevNumber) * parseFloat(currentNumber)
break;
case "/":
result = parseFloat(prevNumber) / parseFloat(currentNumber)
break;
case "%":
result = parseFloat(prevNumber) / 100
break;
default:
return;
}
currentNumber = result
operation = ''
}
equalSign.addEventListener("click", () => {
calculate()
updateScreen(currentNumber)
})
clearBtn.addEventListener("click", () => {
clearAll()
updateScreen(currentNumber)
})
const clearAll = () => {
prevNumber = '';
operation = '';
currentNumber = '0';
}
decimal.addEventListener("click", (e) => {
inputDecimal(e.target.value)
updateScreen(currentNumber)
})
const inputDecimal = (dot) => {
currentNumber += dot
}
const display = document.querySelector("#display");
const buttons = document.querySelectorAll("calculator-keys");
const themeToggleBtn = document.querySelector(".theme-toggler");
const container = document.querySelector(".container");
const toggleIcon = document.querySelector(".toggler-icon");
let isDark = true;
themeToggleBtn.onclick = () => {
container.classList.toggle("dark");
themeToggleBtn.classList.toggle("active");
isDark = !isDark;
};