A Pen by Ezeh Kingsley Uchenna on CodePen.
Created
July 19, 2022 12:49
-
-
Save ezehkingsleyuchenna/659a44e5d8495cc52093f807ebff293d to your computer and use it in GitHub Desktop.
Button Copy Text with JS
This file contains hidden or 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 class="copy-btn" data-text="Hello World">Copy</button> |
This file contains hidden or 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
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