Of course the user can just select the text and copy it but giving them a button that they can click to copy it seems like a better idea(better UX). So in this article I will show you how you can copy text to clipboard using JavaScript.
1. Old method
the old way to copy text to clipboard is
- create a textarea(Or input)
- put the text you want to copy in that textarea
- add textarea to your page
- select the text in textarea
- execute copy command
- remove it from your page
function copyToClipboard(text){
const textArea = document.createElement("textarea")
textArea.value = text
document.body.appendChild(textArea)
textArea.focus()
textArea.select()
document.execCommand('copy')
document.body.removeChild(textArea)
}
2. New method
For newer browsers we can simply use the navigator.clipboard
to copy text
function copyToClipboard(text){
navigator.clipboard.writeText(text)
}
3. Bonus
Now we can combine these two approach and create a function that would use the navigator.clipboard
in modern browsers and fall back to old approach when needed
function copyToClipboard(text){
if(navigator.clipboard){
navigator.clipboard.writeText(text)
return //codes below wont be executed
}
const textArea = document.createElement("textarea")
textArea.value = text
document.body.appendChild(textArea)
textArea.focus()
textArea.select()
document.execCommand('copy')
document.body.removeChild(textArea)
}
Make sure you check out my other articles and YouTube channel.
![0shuvo0](https://res.cloudinary.com/practicaldev/image/fetch/s--wZgMNup---/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res.cloudinary.com/practicaldev/image/fetch/s--j0_lvM9_--/c_fill%2Cf_auto%2Cfl_progressive%2Ch_150%2Cq_auto%2Cw_150/https://dev-to-uploads.s3.amazonaws.com/uploads/user/profile_image/728097/0f6e1da9-f243-42d0-b446-301ac6ea6412.jpeg)
Lets create a screen recorder with JS
Shuvo ・ Oct 21 ・ 3 min read
Top comments (0)