-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
61 lines (49 loc) · 1.75 KB
/
script.js
File metadata and controls
61 lines (49 loc) · 1.75 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
const container = document.querySelector('.container');
for (let i = 0; i < 49; i++) {
const colorBox = document.createElement('div');
colorBox.classList.add('color-box');
const colorCode = document.createElement('span');
colorCode.classList.add('color-code');
colorBox.appendChild(colorCode);
const copyBtn = document.createElement('button');
copyBtn.innerText = "Copy";
colorBox.appendChild(copyBtn);
container.appendChild(colorBox);
}
function randomColor() {
const chars = "0123456789ABCDEF";
const colCodeLen = 6;
let colorCode = "";
for (let i = 0; i < colCodeLen; i++) {
const randomNum = Math.floor(Math.random() * 16);
colorCode += chars.substring(randomNum, randomNum + 1);
}
return colorCode;
}
const colContElems = document.querySelectorAll('.color-box');
genColor();
function genColor() {
for (let i = 0; i < colContElems.length; i++) {
const colorBox = colContElems[i];
const newColCode = randomColor();
const colorCode = colorBox.querySelector('.color-code');
colorBox.style.backgroundColor = "#" + newColCode;
colorCode.innerText = "#" + newColCode;
}
}
colContElems.forEach((colorBox) => {
const copyBtn = colorBox.querySelector('button');
const colorCode = colorBox.querySelector('.color-code');
copyBtn.addEventListener('click', () => {
copyToClipboard(colorCode.innerText);
})
})
function copyToClipboard(text) {
navigator.clipboard.writeText(text)
.then(() => {
alert("Color code copied to clipboard : " + text);
})
.catch((err) => {
console.error("Failed to copy the color code :(", err);
});
}