You can copy text in JavaScript with the click of a button by using the clipboard.writeText()
method from the Clipboard API. Here’s an example:
<button id="copy-button">Copy Text</button>
<script>
const copyButton = document.getElementById("copy-button");
copyButton.addEventListener("click", function() {
navigator.clipboard.writeText("This text will be copied.").then(function() {
console.log("Text copied successfully.");
}, function(err) {
console.error("Failed to copy text: ", err);
});
});
</script>
In this example, we get a reference to the button element and attach a click event listener to it. When the button is clicked, the writeText()
method is called with the text that we want to copy. The method returns a promise that resolves if the text was copied successfully and rejects if an error occurred.
Note that this feature is supported in modern browsers, but may not work in older browsers.
+ There are no comments
Add yours