-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
75 lines (65 loc) · 2.28 KB
/
index.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
let main = document.querySelector('main');
let root = document.querySelector(':root');
let input = document.getElementById('input');
let resultInput = document.getElementById('result');
let allowedKeys = [
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
"(", ")", "+", "-", "*", "/", "%", ".", " "
];
document.querySelectorAll('.charKey').forEach(function (charKeyBtn){
charKeyBtn.addEventListener('click', function() {
let value = charKeyBtn.dataset.value;
input.value += value;
});
});
document.getElementById('clear').addEventListener('click', function (){
input.value = '';
input.focus();
})
input.addEventListener('keydown', function(ev) {
ev.preventDefault();
if (allowedKeys.includes(ev.key)) {
input.value += ev.key;
return;
}
if(ev.key == 'Backspace') {
input.value = input.value.slice(0, -1);
}
if(ev.key == 'Enter') {
calculate()
}
});
document.getElementById('equal').addEventListener('click', calculate);
function calculate() {
resultInput.value = 'ERROR';
resultInput.classList.add('error');
let result = eval(input.value);
resultInput.value = result;
resultInput.classList.remove('error');
}
document.getElementById('themeSwitcher').addEventListener('click', function (){
if (main.dataset.theme == 'dark') {
root.style.setProperty('--bg-color', '#f1f5f9');
root.style.setProperty('--border-color', '#aaa');
root.style.setProperty('--font-color', '#212529');
root.style.setProperty('--primary-color', '#26834a');
main.dataset.theme = 'light';
} else {
root.style.setProperty('--bg-color', '#212529');
root.style.setProperty('--border-color', '#666');
root.style.setProperty('--font-color', '#f1f5f9');
root.style.setProperty('--primary-color', '#4dff91');
main.dataset.theme = 'dark';
}
});
document.getElementById('copyToClipboard').addEventListener('click', function(ev){
let button = ev.currentTarget;
if(button.innerText == 'Copy') {
button.innerText = 'Copied!';
button.classList.add('success');
window.navigator.clipboard.writeText(resultInput.value);
} else {
button.innerText = 'Copy';
button.classList.remove('success');
}
});