Skip to content

Instantly share code, notes, and snippets.

@mattstabeler
Last active January 28, 2022 12:51
Show Gist options
  • Save mattstabeler/eebec15d4903c46ebfa036a947e5b33d to your computer and use it in GitHub Desktop.
Save mattstabeler/eebec15d4903c46ebfa036a947e5b33d to your computer and use it in GitHub Desktop.
Copy data to clipboard
<button data-clipboard-copy-content="copy this content">Copy</button>
function copyToClipboard(data) {
// Create a "hidden" input
var aux = document.createElement("input");
// Assign it the value of the specified element
aux.setAttribute("value", data);
// Append it to the body
document.body.appendChild(aux);
// Highlight its content
aux.select();
// Copy the highlighted text
document.execCommand("copy");
// Remove it from the body
document.body.removeChild(aux);
}
// using javascript
var clickers = document.querySelectorAll('[data-clipboard-copy-content]');
for (var i = clickers.length - 1; i >= 0; i--) {
clickers[i].addEventListener("click", function(ev) {
copyToClipboard(ev.target.dataset.clipboardCopyContent);
});
}
//using jQuery
$('[data-clipboard-copy-content]').click(function(ev) {
copyToClipboard(ev.target.dataset.clipboardCopyContent);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment