-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
88 lines (49 loc) · 2.06 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
const inputScreen = document.getElementById('operations');
const btnDiv = document.getElementById('buttons');
const opBtns = document.querySelectorAll('.op-btn');
const generateButtons = () => {
const clearBtn = document.createElement('button');
clearBtn.setAttribute('class', 'calc-btn clear');
clearBtn.innerText = 'C';
clearBtn.addEventListener('click', () => inputScreen.innerText = '');
const equalBtn = document.createElement('button');
equalBtn.setAttribute('class', 'calc-btn equal');
equalBtn.innerText = '=';
equalBtn.addEventListener('click', calculate);
for (let number = 1; number <= 10; number++) {
const numberButton = document.createElement('button');
numberButton.setAttribute('class', 'calc-btn');
numberButton.innerText = (number == 10) ? 0 : number;
numberButton.addEventListener('click', () => inputScreen.innerText += numberButton.innerText);
btnDiv.append(numberButton);
}
btnDiv.append(clearBtn);
btnDiv.append(equalBtn);
}
const ops = ['+', '*', '/'];
opBtns.forEach(btn => {
btn.addEventListener('click', () => {
const operation = btn.dataset.operation;
if (inputScreen.innerText != '') {
const values = inputScreen.innerText.split('');
const lastValueOfInputScreen = values[values.length - 1];
if (lastValueOfInputScreen == '-') {
inputScreen.innerText.replace(inputScreen.innerText[inputScreen.innerText.length - 1], '-');
}
else if (lastValueOfInputScreen != operation && (!ops.includes(lastValueOfInputScreen))) {
inputScreen.innerText += operation
}
} else {
if (operation == '-') inputScreen.innerText += operation;
}
});
});
const calculate = () => {
if (inputScreen.innerText == '' || inputScreen.innerText == 'Error') return;
try {
inputScreen.innerText = eval(inputScreen.innerText);
} catch (error) {
inputScreen.innerText = 'Error';
}
}
generateButtons()