DEV Community

Cover image for Copy text to clipboard in JS(two ways)
Shuvo
Shuvo

Posted on

11 1

Copy text to clipboard in JS(two ways)

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 ```js

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)
Enter fullscreen mode Exit fullscreen mode

}


## 2. New method
For newer browsers we can simply use the `navigator.clipboard` to copy text
```js


function copyToClipboard(text){
    navigator.clipboard.writeText(text)
}


Enter fullscreen mode Exit fullscreen mode

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)
}


Enter fullscreen mode Exit fullscreen mode

Make sure you check out my other articles and YouTube channel.


Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more