Last active
January 28, 2022 12:51
-
-
Save mattstabeler/eebec15d4903c46ebfa036a947e5b33d to your computer and use it in GitHub Desktop.
Copy data to clipboard
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<button data-clipboard-copy-content="copy this content">Copy</button> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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