Not able copy to clipboard It is a color picker random generator
on click of button it not copy hexcode to the clipboard
it is giving error Uncaught typeerror copyText.select is not function
navigator.clipboard.writeText or navigator.clipboard.write
const hex = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"];
const btn = document.getElementById("button");
const color = document.querySelector(".color");
btn.addEventListener("click", function() {
let hexColor = "#";
for (let i = 0; i < 6; i ) {
hexColor = hex[getRandomNumber()];
}
color.textContent = hexColor;
document.body.style.backgroundColor = hexColor;
});
function getRandomNumber() {
return Math.floor(Math.random() * hex.length);
}
function myFunction() {
let copyText = document.getElementById("color-code");
console.log("copytext" copyText);
copyText.select();
navigator.clipboard.write(copyText.value);
alert("Copied the text: " copyText.value);
}
<section >
<div >
<div >
<div >
<div >
<div >
<div >
<h3 >
<span> Background Color <span id="color-code">hexcode </span>
</span>
</h3>
<button id="copyColorHex" onclick="myFunction()">
<span >
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
</svg>
</span>
</button>
</div>
</div>
</div>
</div>
</div>
<div >
<div >
<button id="button">click me</button>
</div>
</div>
</div>
</section>
Thanks in advanced
CodePudding user response:
select()
is only available on<input>
and<textarea>
elements. You can make an<input readonly>
to hold the color output (in itsvalue
attribute, rather than the content of a<span>
).It looks like you might be mixing up clipboard copying strategies.
navigator.clipboard.write
doesn't require you to select text first. But if you're doing that as a fallback for browsers that don't supportnavigator.clipboard.write
that's fine.
CodePudding user response:
You can pass the text you wish to copy directly as a parameter of the navigator.clipboard.writeText() without the need of selecting it but be careful when you use this method as it won't work in various online editors like jsfiddle. It worked fine with me in vs code.