Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ezehkingsleyuchenna/659a44e5d8495cc52093f807ebff293d to your computer and use it in GitHub Desktop.
Save ezehkingsleyuchenna/659a44e5d8495cc52093f807ebff293d to your computer and use it in GitHub Desktop.
Button Copy Text with JS
<button class="copy-btn" data-text="Hello World">Copy</button>
const copy = (text) => {
let elem = document.createElement('input');
document.body.appendChild(elem);
elem.value = text; elem.select();
document.execCommand("copy");
alert("Copied!");
elem.remove();
}
// onload of html
window.onload = () => {
const copyBtn = document.getElementsByClassName('copy-btn');
for (let i = 0 ; i < copyBtn.length; i++) {
copyBtn[i].addEventListener('click' , () => {
const attributeText = copyBtn[i].getAttribute('data-text');
copy(attributeText);
} , false) ;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment