Created
September 25, 2018 16:14
-
-
Save ewliang/6fbfb028a495db2e4a3a85b864356687 to your computer and use it in GitHub Desktop.
Vanilla JavaScript for creating a button that allows users to copy a hardcoded element's text content.
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
/* HTML | |
<p id="text_element">I am the text that the button will allow you to copy.</p> | |
<button onclick="copyToClipboard('text_element')"> | |
Copy | |
</button> | |
*/ | |
function copyToClipboard(elementId) { | |
// Create an auxiliary hidden input. | |
// Reason: The hidden aux input will act as a temporary container for our code to select via highlighting and copying since it's easier to do it on an input element. | |
var aux = document.createElement("input"); | |
// Get the text from the element passed into the input | |
aux.value = document.getElementById(elementId).innerHTML; | |
// Append the aux input to the body | |
document.body.appendChild(aux); | |
// Highlight the content | |
aux.select(); | |
// Execute the copy command | |
document.execCommand("copy"); | |
// Remove the input from the body | |
document.body.removeChild(aux); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment