Snippet JS copy to clipboard full support old browser and modern browser Snippet fallback copy to clipboard for old browser function fallbackCopyTextToClipboard
Snippet fallback copy to clipboard for old browser
function fallbackCopyTextToClipboard(text) {
var textArea = document.createElement("textarea");
textArea.value = text;
// Avoid scrolling to bottom
textArea.style.top = "0";
textArea.style.left = "0";
textArea.style.position = "fixed";
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
var successful = document.execCommand("copy");
var msg = successful ? "successful" : "unsuccessful";
console.log("Fallback: Copying text command was " + msg);
} catch (err) {
console.error("Fallback: Oops, unable to copy", err);
}
document.body.removeChild(textArea);
}
Snippet copy to clipboard for modern browser
function copyTextToClipboard(text) {
if (!navigator.clipboard) {
fallbackCopyTextToClipboard(text);
return;
}
navigator.clipboard.writeText(text).then(
function () {
console.log("Async: Copying to clipboard was successful!");
},
function (err) {
console.error("Async: Could not copy text: ", err);
}
);
}
Usage copy to cliboard Snippet
copyTextToClipboard('Text to copy');
Full Example copy to clipboard javascript and html
<div style="display: inline-block; vertical-align: top">
<button class="js-copy-1-btn">Set clipboard</button><br><br>
<button class="js-copy-2-btn">Set clipboard</button>
</div>
<div style="display: inline-block">
<textarea class="js-test-textarea" cols="35" rows="4">
Paste here (CTRL+V or HOLD, touch and paste) to see what's on your clipboard.
</textarea>
</div>
<script>
function fallbackCopyTextToClipboard(text) {
var textArea = document.createElement("textarea");
textArea.value = text;
// Avoid scrolling to bottom
textArea.style.top = "0";
textArea.style.left = "0";
textArea.style.position = "fixed";
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
var successful = document.execCommand("copy");
var msg = successful ? "successful" : "unsuccessful";
console.log("Fallback: Copying text command was " + msg);
} catch (err) {
console.error("Fallback: Oops, unable to copy", err);
}
document.body.removeChild(textArea);
}
function copyTextToClipboard(text) {
if (!navigator.clipboard) {
fallbackCopyTextToClipboard(text);
return;
}
navigator.clipboard.writeText(text).then(
function () {
console.log("Async: Copying to clipboard was successful!");
},
function (err) {
console.error("Async: Could not copy text: ", err);
}
);
}
var copyBobBtn = document.querySelector(".js-copy-1-btn"),
copyJaneBtn = document.querySelector(".js-copy-2-btn");
copyBobBtn.addEventListener("click", function (event) {
copyTextToClipboard("Text 1 to be copied");
});
copyJaneBtn.addEventListener("click", function (event) {
copyTextToClipboard("Text 2 to be copied");
});
</script>