articles » current » javascript » copy-text-to-clipboard

JavaScript: Copy Text to Clipboard

How to copy text to the clipboard with Chrome, Edge, Firefox and Internet Explorer

This code will copy text to the clipboard, and it is compatible with IE, Edge, Firefox, Chrome and Safari.

Basically, if not using IE, create a textarea element and set its value to the text to copy and then select it and issue a copy command. It is important that the code execute in response to a user event like a click on something. Do not hide the textarea element in any way because it will not allow the copy operation.

If using IE, then it is a very simple affair.

function copyToClipboard(textData) {
	if (window.clipboardData) { // this is for Internet Explorer
		window.clipboardData.setData("Text", textData);
	}
	else { // this is for Edge, Firefox, Chrome and Safari; this also works with IE, but it does not work as smoothly as above code causing the page to jump around
		var t = document.createElement("textarea"); // create textarea element
		t.value = textData; // set its value to the data to copy
		t.style.position = "absolute";
		t.style.display = "inline";
		t.style.width = t.style.height = t.style.padding = 0;
		t.setAttribute("readonly", ""); // textarea is readonly
		document.body.appendChild(t); // append the textarea element - may be better to append to the object being clicked
		t.select(); // select the data in the text area
		document.execCommand("copy"); // IMPORTANT: "copy" works as a result of user events, like "click" event
		document.body.removeChild(t); // remove the textarea element
	}
	alert("Text data has been copied to the clipboard.");
	return false;
}

Example usage:

<html>
<head>
	<title>Copy To Clipboard Example</title>
	<script type="text/javascript">
		function copyToClipboard(textData) {
			if (window.clipboardData) {
				window.clipboardData.setData("Text", textData);
			}
			else {
				var t = document.createElement("textarea");
				t.value = textData;
				t.style.position = "absolute";
				t.style.display = "inline";
				t.style.width = t.style.height = t.style.padding = 0;
				t.setAttribute("readonly", "");
				document.body.appendChild(t);
				t.select();
				document.execCommand("copy");
				document.body.removeChild(t);
			}
			alert("Text data has been copied to the clipboard.");
			return false;
		}
	</script>
</head>
<body>
<pre style="cursor:pointer;" onclick="copyToClipboard(this.innerText);">This is preformatted text.
Click on it to copy it to the clipboard.
Bla bla bla bla bla.</pre>
<a href="javascript:;" onclick="return copyToClipboard(this.innerText);">click here to copy this text to the clipboard.</a>
</body>
</html>

Coding Video

https://youtu.be/lDrRbaaopxs


This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
CLOSE