Follow @endyourif rss Facebook LinkedIn

Copy text to clipboard using Javascript Copy text to clipboard using Javascript

Published on Jun 13, 2022

As a user of almost any website, it's so nice when a website allows you to easily copy something to the clipboard so you don't need to select the text press Ctrl+C or if you watch people who don't use shortcuts and instead right click and select the copy option.

Because Javascript is a client side language, browsers have to enforce some security so malicious sites can't do bad things to your computer with JavaScript array, thus making the process slightly more cumbersome. Here is some pseudo code of how to accomplish it:

1. Check the queryCommandSupported for the copy command
2. Create textarea form element
3. Set the text content to the data you wish to copy to the clipboard
4. Set the position of the textarea so it will not be visible while this process happens
5. Append the textarea to the DOM
6. Select the contents of the textarea
7. Run the execCommand function

Let's take a look at the function to copy text to the clipboard with Javascript:

function copyToClipboard(text) {
if (document.queryCommandSupported && document.queryCommandSupported("copy")) {
var textarea = document.createElement("textarea");
textarea.textContent = text;
// Prevent scrolling to bottom of page in Microsoft Edge. = "fixed";

// Security exception may be thrown by some browsers.
try {
return document.execCommand("copy");
catch (ex) {
console.warn("Copy to clipboard failed.", ex);
return prompt("Copy to clipboard: Ctrl+C, Enter", text);
finally {

Some users will have stricter rules for what Javascript will do that the execCommand function is wrapped in a try/catch so that if a browser throws an error a helpful prompt will be displayed that will allow the user to press Ctrl+C then enter to manually copy the text. And finally the textarea is removed from the DOM regardless of success or failure.

Tags: JavaScript | clipboard

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP