JavaScript Copy Text to Clipboard

by Vincy. Last modified on December 5th, 2023.

This example script in JavaScript is to copy text to the system clipboard. I am presenting three different methods in this tutorial.

  1. Via ClipBoard API.
  2. Using document.executeCommand (not recommended).
  3. By user consent.

View demo
This JS quick example uses the first and the best method to copy content of a textarea to the clipboard.

Quick example

var contentToCopy = document.getElementById(text_to_copy).value;
navigator.clipboard.writeText(contentToCopy).then(function() {
	console.log('Copied to clipboard with async.');
}, function(err) {
	console.error('Unable to copy with async ', err);
});

HTML textarea element from where the content is copied by the JS script.

<textarea id="text_to_copy">Text to copy</textarea>

javascript copy clipboard

1) Using The Clipboard API

Below HTML script gives an interface with a textarea and a button to trigger the copy action.

On clicking the button to call the JavaScript copyToClipBoard() function. This function moves the textarea content to the clipboard.

index.html

<html>
<head>
<title>JavaScript Copy Text to Clipboard</title>
<script src="copy-clipboard-async.js"></script>
<script src="https://code.jquery.com/jquery-3.6.1.min.js"
    integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ="
    crossorigin="anonymous"></script>
<link rel='stylesheet' href='style.css' type='text/css' />
<link rel='stylesheet' href='form.css' type='text/css' />
</head>
<body>
    <div class="phppot-container">
        <h1>JavaScript Copy Text to Clipboard</h1>
        <div class="row">
            <div class="message-input">
                <label for="message-input">Message: </label>
                <textarea id="message-input" rows="15"
                    name="message-input" class="message-input"></textarea>
            </div>
        </div>
        <div class="row">
            <button onclick="copyToClipboard('message-input')"
                type="button">Copy to clipboard</button>
        </div>
        <div class="row">
            <div id="copied"></div>
        </div>
    </div>
</body>
</html>

This JS script writes the text to the clipboard by calling clipboard.writeText(). It enhances the quick example by providing an interface to copy content via ClipBoard API.

copy-clipboard-async.js

/**
 * to copy to the clipboard using the Clipboard API
 * 
 * @param element
 * @returns
 */
function copyToClipboard(element) {
	var contentToCopy = document.getElementById(element).value;
	navigator.clipboard.writeText(contentToCopy).then(function() {
		console.log('Copied to clipboard with async.');
	}, function(err) {
		console.error('Unable to copy with async ', err);
	});
}

2) document.execCommand

This method was widely used to copy content by calling the executeCommand(“copy”). It is deprecated but still supported by many browsers.

It dynamically appends the textarea element to the HTML body and selects its content using JavaScript. Then the executeCommand() function call triggers the copy action.

copy-clipboard-execcommand.js

/**
 * to copy to the clipboard using the document.execCommand
 * 
 * @param element
 * @returns
 */
function copyToClipboard(element) {
	var contentToCopy = document.getElementById(element).value;
	var temp = $("<textarea>");
	$("body").append($temp);
	temp.val(contentToCopy);
	temp.select();
	document.execCommand("copy");
	temp.remove();
	console.log('Copied!');
}

3) Copy by user

This is the safest method of copying the content to the clipboard. This does not use any native function of the JavaScript and can be described more of a process. It prompts the user to confirm copying the selected content to the clipboard.

copy-by-user-consent.html

<html>
<head>
<title>JavaScript Copy Text to Clipboard</title>
</head>
<body>
    <!-- In this style, we present the control to the end user to copy.  -->
    <!-- Text to be copied is shown to the user and he uses the built-in browser's feature and copies to the clipboard. -->
    <!-- If this is possible to use in your use case, then this is the safest method. -->
    <button id="copy-btn"
        onclick="copyToClipboard(document.getElementById('copy-btn').innerHTML)">Text
        to copy.</button>
    <script>
		function copyToClipboard(text) {
			window.prompt("Press Ctrl+C to copy to clipboard.",
					text);
		}
	</script>
</body>
</html>

View demo Download

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Leave a Reply

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

↑ Back to Top

Share this page