⚠️ Legacy Content Notice: This post was originally written in 2016 and discusses the deprecated
document.execCommand
method. While the content remains for historical reference, modern web development should use the Clipboard API instead. For comprehensive modern JavaScript development practices, see our Modern JavaScript Development Guide.
In a previous tutorial we saw how you can create a copy and paste button using jQuery and the ZeroClipboard flash
extension. The problem with this is that it requires flash. As most of the web is moving away from flash and some people
don't even have flash installed on their browser we need another solution. The reason flash was used to copy and paste
is mainly down to browser compatibility, now with most browsers now supporting the API to enable you to copy and paste
directly using Javascript using the Web API document.execCommand
. View the demo to see how the API works
HTML
First we add the HTML to the page we need a textbox to enter the content we want to copy, a button that will have the click event to start the copy process and a textarea where we can test the copy is successful by pasting the contents into it.
<div>
<input type="text" id="text-to-copy" placeholder="Enter text" />
<button id="copy-text">Copy</button>
<span id="copied-text" style="display: none;">Copied!</span>
</div>
<div>
<textarea
name="paste-area"
id="paste-area"
cols="30"
rows="10"
placeholder="Paste it here"
></textarea>
</div>
Copy Text
To copy the text we first need to add a click event to the button.
document.getElementById("copy-text").addEventListener("click", function (e) {
// Click event
});
Inside the click event we need to select the text inside the textbox.
document.getElementById("text-to-copy").select();
With the text selected we can now use the execCommand('copy')
to copy the text to the clipboard.
copied = document.execCommand("copy");
The return of this method will be a boolean on if the text was copied or not, you can then check this boolean value to display a message if it was able to be copied.
// Add click event
document.getElementById("copy-text").addEventListener("click", function (e) {
e.preventDefault();
// Select the text
document.getElementById("text-to-copy").select();
var copied;
try {
// Copy the text
copied = document.execCommand("copy");
} catch (ex) {
copied = false;
}
if (copied) {
// Display the copied text message
document.getElementById("copied-text").style.display = "block";
}
});
Modern Alternative: Clipboard API
⚠️ The document.execCommand('copy')
method shown above is deprecated. Here's the modern approach using the Clipboard API:
async function copyToClipboard(text) {
try {
await navigator.clipboard.writeText(text);
console.log("Text copied to clipboard");
return true;
} catch (err) {
console.error("Failed to copy text: ", err);
return false;
}
}
// Modern copy implementation
document
.getElementById("copy-text")
.addEventListener("click", async function (e) {
e.preventDefault();
const textToCopy = document.getElementById("text-to-copy").value;
const success = await copyToClipboard(textToCopy);
if (success) {
document.getElementById("copied-text").style.display = "block";
// Hide the message after 2 seconds
setTimeout(() => {
document.getElementById("copied-text").style.display = "none";
}, 2000);
}
});
Reading from Clipboard
You can also read from the clipboard using the modern API:
async function readFromClipboard() {
try {
const text = await navigator.clipboard.readText();
return text;
} catch (err) {
console.error("Failed to read clipboard contents: ", err);
return null;
}
}
// Example usage
document
.getElementById("paste-button")
.addEventListener("click", async function () {
const clipboardText = await readFromClipboard();
if (clipboardText) {
document.getElementById("paste-area").value = clipboardText;
}
});
Feature Detection
Always check for Clipboard API support:
function canUseClipboardAPI() {
return navigator.clipboard && window.isSecureContext;
}
if (canUseClipboardAPI()) {
// Use modern Clipboard API
copyToClipboard(text);
} else {
// Fallback to legacy method (if necessary)
legacyCopyToClipboard(text);
}
Quick Navigation
- 📖 Modern JavaScript Development Guide - Comprehensive guide to modern JS practices
- 🔧 JavaScript Helper Functions - Useful utility functions
- 💾 Local Storage vs Session Storage - Browser storage options