I'm trying to apply a copy to clipboard option on my color selecctor, which shows up the color selected on a h3 tag.The idea is to make a background color generator in which each time a color is selected, it would appear on screen, allowing us to select all the information of the colors and then being able to copy said color information to our clipboard by clicking on the botton. I don't kown why the button doesn't work.
I'm still learging how properly use these methods, but I couldn't make it work yet. Any advice would be greatly appreciated.
var css = document.querySelector("h3");
var color1 = document.querySelector(".color1");
var color2 = document.querySelector(".color2");
var color3 = document.querySelector(".color3");
var body = document.getElementById("gradient");
var button = document.querySelector("button");
function setGradient() {
body.style.background =
"linear-gradient(to right, "
+ color1.value
+ ", "
+ color2.value
+ ", "
+ color3.value
")";
css.textContent = body.style.background + ";";
}
/*Not working yet!*/
function copyElement(){
if(setGradient){
/*Getting the textfield*/
var copyText = css.textContent;
/*Selecting the text field */
copyText.select();
copyText.setSelectionRange(0,99999);
/*Copying text*/
document.execCommand("copy");
alert("Copied!");
}
}
color1.addEventListener("input",setGradient);
color2.addEventListener("input",setGradient);
color3.addEventListener("input",setGradient);
button.addEventListener("click",copyElement);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Gradient Background</title>
<link rel="stylesheet" href="style.css">
</head>
<body id="gradient">
<h1>Background Generator</h1>
<input class="color1" type="color" name="color1" value="#00ff00">
<input class="color2" type="color" name="color2" value="#ffff00">
<input type="color" class="color3" name="color3" value="#AF0066">
<h2>Current CSS Backgrounds</h2>
<h2>Deluxe edition </h2>
<h3></h3>
<input type="button" class="button" name="button" value="Copy to clipboard">
<script type="text/javascript" src="script.js"></script>
</body>
</html>