-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
60 lines (51 loc) · 2.28 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
const colorPickerBtn = document.querySelector("#color-picker");
const colorList = document.querySelector(".all-colors");
const clearAll = document.querySelector(".clear-all");
const pickedColors = JSON.parse(localStorage.getItem("picked-colors") || "[]");
// Copying the color code to the clipboard and updating the element text
const copyColor = elem => {
navigator.clipboard.writeText(elem.dataset.color);
elem.innerText = "Copied";
setTimeout(() => elem.innerText = elem.dataset.color, 1000)
}
const showColors = () => {
if (!pickedColors.length) return; //returning if there are no picked colors
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" data-color="${color}">${color}</span>
</li>
`).join(""); //Generating li for the picked color and adding it to the colorList.
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();
const activateEyeDropper = () => {
document.body.style.display = "none";
setTimeout(async () => {
try {
const eyeDropper = new EyeDropper();
const { sRGBHex } = await eyeDropper.open();
navigator.clipboard.writeText(sRGBHex);
if (!pickedColors.includes(sRGBHex)) {
pickedColors.push(sRGBHex);
localStorage.setItem("picked-colors", JSON.stringify(pickedColors));
showColors();
}
} catch (error) {
console.log("Failed to copy the color code!");
}
document.body.style.display = "block";
}, 10);
}
// Clearing all picked colors, updating localstorage, and hiding the pickedColors element
const clearAllColors = () => {
pickedColors.length = 0;
localStorage.setItem("picked-colors", JSON.stringify(pickedColors));
document.querySelector(".picked-colors").classList.add("hide");
}
clearAll.addEventListener("click", clearAllColors);
colorPickerBtn.addEventListener("click", activateEyeDropper);