Snippet JS copy to clipboard full support old browser and modern browser
Snippet fallback copy to clipboard for old browser
functionfallbackCopyTextToClipboard(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
functioncopyTextToClipboard(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
<divstyle="display: inline-block; vertical-align: top"><buttonclass="js-copy-1-btn">Set clipboard</button><br /><br /><buttonclass="js-copy-2-btn">Set clipboard</button></div><divstyle="display: inline-block"><textareaclass="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>functionfallbackCopyTextToClipboard(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); }functioncopyTextToClipboard(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>