-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
64 lines (49 loc) · 1.8 KB
/
script.js
File metadata and controls
64 lines (49 loc) · 1.8 KB
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
document.addEventListener("DOMContentLoaded", () => {
const binaryInput = document.getElementById("binary");
const decimalOutput = document.getElementById("decimal-number");
const copyButton = document.getElementById("copy-button");
binaryInput.value = ""; // resets input after reload
binaryInput.addEventListener("input", updateDecimalOutput);
copyButton.addEventListener("click", copyToClipboard);
const containsInvalidChars = (arr) =>
arr.some((bit) => bit !== "0" && bit !== "1");
function handleInvalidInput() {
alert("This character is not permitted!");
binaryInput.value = "";
decimalOutput.innerText = "-";
}
function updateDecimalOutput() {
const binaryInputArray = binaryInput.value.split("");
if (containsInvalidChars(binaryInputArray)) {
handleInvalidInput();
return;
}
decimalOutput.innerHTML = binaryInputArray.every((bit) => bit === "0")
? 0
: parseInt(binaryInput.value, 2);
}
function copyToClipboard() {
const textToCopy = decimalOutput.innerText;
if (decimalOutput.innerHTML !== "-") {
const tempTextarea = document.createElement("textarea");
tempTextarea.value = textToCopy;
document.body.appendChild(tempTextarea);
tempTextarea.select();
tempTextarea.setSelectionRange(0, 99999);
document.execCommand("copy");
document.body.removeChild(tempTextarea);
} else {
alert("Can't copy if there isn't anything to copy.");
}
}
let toggleMode = document.querySelector("#toggle-mode");
toggleMode.addEventListener("click", () => {
document.documentElement.classList.toggle("dark-mode");
});
if (
window.matchMedia &&
window.matchMedia("(prefers-color-scheme: dark)").matches
) {
document.documentElement.classList.toggle("dark-mode");
}
});