Skip to content

How to Copy Text to Clipboard using JavaScript

  • by

In this article, you will learn how to write (copy) text and images to the 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.

When you’re building advanced web pages and applications, you’ll sometimes want to add the copy feature. This lets your users simply click a button or icon to copy text rather than highlighting the text and clicking a couple of buttons on the keyboard.

In case you are in a rush, here is the code:

Copy Text to Clipboard :

HTML

<input type="text" value="Welcome to QuickMySupport" 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>

In this article, you have learned how to copy text to the clipboard using JavaScript.

Leave a Reply

Your email address will not be published. Required fields are marked *