How to Copy Text to Clipboard using JavaScript

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>

Leave a reply

keyboard_double_arrow_up