-
Notifications
You must be signed in to change notification settings - Fork 0
/
popup.js
76 lines (66 loc) · 2.51 KB
/
popup.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
//Getting elements and picked colors from local storage
const colorPickerBtn = document.querySelector("#color-picker");
const clearAllBtn = document.querySelector(".clear-all");
const colorList = document.querySelector(".all-colors");
const pickedColors = JSON.parse(localStorage.getItem("picked-colors") || "[]");
// Function to copy the color code to the clipboard and update the element text
const copyColor = (elem) => {
elem.innerText = "Copied";
navigator.clipboard.writeText(elem.dataset.color);
setTimeout(() => (elem.innerText = elem.dataset.color), 1000);
};
// Function to show picked colors
const showColors = () => {
if (!pickedColors.length) return;
// Generate li for the picked color and add it to the colorList
colorList.innerHTML = pickedColors
.map(
(color) => `
<li class="color">
<span class="rect" style="background: ${color}; border: 1px solid ${
color == "#ffffff" ? "#ccc" : color
}"></span>
<span class="value hex" data-color="${color}">${color}</span>
</li>
`
)
.join("");
document.querySelector(".picked-colors").classList.remove("hide");
// Add a click event listener to each color element to copy the color code
document.querySelectorAll(".color").forEach((li) => {
li.addEventListener("click", (e) =>
copyColor(e.currentTarget.lastElementChild)
);
});
};
showColors();
// Function to get the selected color
const activateEyeDropper = () => {
document.body.style.display = "none";
setTimeout(async () => {
try {
// Open the eye dropper
const eyeDropper = new EyeDropper();
const { sRGBHex } = await eyeDropper.open();
navigator.clipboard.writeText(sRGBHex);
// Add the color to the list if it doesn't already exist
if (!pickedColors.includes(sRGBHex)) {
pickedColors.push(sRGBHex);
localStorage.setItem("picked-colors", JSON.stringify(pickedColors));
showColors();
}
} catch (error) {
alert("Failed to copy the color code!");
}
document.body.style.display = "block";
}, 10);
};
// Function to clear all picked colors, update local storage, and hide the colorList element
const clearAllColors = () => {
pickedColors.length = 0;
localStorage.setItem("picked-colors", JSON.stringify(pickedColors));
document.querySelector(".picked-colors").classList.add("hide");
};
// Add event listeners to buttons
clearAllBtn.addEventListener("click", clearAllColors);
colorPickerBtn.addEventListener("click", activateEyeDropper);