Generally, the key combination (CTRL+C) of the keyboard is used to copy text to clipboard. If you want to integrate copy to clipboard functionality on button click, JavaScript is the easiest option to do that. The HTML DOM execCommand() method provides a simple way to copy text to clipboard.
The execCommand() executes a specific command for a selected section of the document. You can use the copy
command with document.execCommand() to copy text content to clipboard using JavaScript. In the example code snippet, we will show you how to copy text to clipboard with JavaScript.
The following code copies text from the input text field to clipboard on button click using execCommand in JavaScript.
HTML
<input type="text" value="Welcome to CodexWorld" id="textInput">
<button onclick="copyText()">Copy text</button>
JavaScript
<script>
function copyText(){
var text = document.getElementById("textInput");
text.select();
document.execCommand("copy");
alert("Copied the text: " + text.value);
}
</script>
The following code snippet helps you to copy Text/HTML content to clipboard from <div> element using JavaScript.
HTML:
Let’s assume that we have <div> tag with text content and button to copy text from it.
<div class="text-to-copy">Let's copy the text from here...</div>
<button class="copy-button">Copy</button>
JavaScript:
Use the navigator to copy text to clipboard using JavaScript.
// Select button element
let button = document.querySelector(".copy-button");
// Get inner content from div
let textToCopy = document.querySelector(".text-to-copy").innerHTML;
// Copy text to the clipboard
button.addEventListener("click", () => {
navigator.clipboard.writeText(textToCopy);
});