-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
65 lines (54 loc) · 1.9 KB
/
app.js
File metadata and controls
65 lines (54 loc) · 1.9 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
65
const hex = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"];
const buttons = document.getElementsByClassName("hexcode");
//console.log(buttons); so these are all my buttons
const colors = document.getElementsByClassName("color");
//console.log(colors); all the colors
for(let i=0;i<buttons.length;i++){
let button = buttons[i];
let color = colors[i];
button.addEventListener("click", function() {
let newColor = getRandomHex();
color.style.backgroundColor = newColor;
color.style.color =newColor;
button.textContent = newColor;
});
color.addEventListener("click", function() {
//this does not work to copy to clipboard
//write to the clipboard
//this does though, we can use select and execCommand copy only when we have an input field
let tocopy = button.textContent;
copyStringToClipboard(tocopy);
//alert("Copied!");
//copied! signal
let x = document.getElementById("snackbar");
x.style.visibility = "visible";
setTimeout(function(){x.style.visibility = "hidden";},1000)
});
}
function getRandomNumber() {
return Math.floor(Math.random() * hex.length);
}
function getRandomHex() {
let hexColor = "#";
for (let i = 0; i < 6; i++) {
hexColor += hex[getRandomNumber()];
}
return hexColor;
}
function copyStringToClipboard (str) {
// Create new element
var el = document.createElement('textarea');
// Set value (string to be copied)
el.value = str;
// Set non-editable to avoid focus and move outside of view
el.setAttribute('readonly', '');
el.style = {position: 'absolute', left: '-9999px'};
document.body.appendChild(el);
// Select text inside element
el.select();
// Copy text to clipboard
document.execCommand('copy');
// Remove temporary element
document.body.removeChild(el);
}
//CAUTION: Script added at the end of HTML document or it will run before the oage loads and I'll get errors(null)