How to copy text to clipboard with Javascript

As developers, we all know how useful it is to have a "copy" button sitting next to a block of code. It helps a lot in increasing the usability of our web apps.

In this post, we'll see how to use the Clipboard API to copy text to the clipboard on a button click.

Here's what we are building.

Enter some text into input field and click Copy button.

Ok, Let's get started.

First let's create a simple input and button with some styling.

Now it's time to add Javascript.

We'll start by getting element references to all required elements. Then, add click event listener to the Copy button.

On Copy button click event, check if the browser supports Clipboard API. If supported use navigator.clipboard.writeText() otherwise fallback to document.execCommand('copy') method to copy text to the clipboard.

There's a lot happening in copyWithEXECCommand(text).

Start by getting the active element and current selection for setting it back later.

Then create a textarea element, set styles to make it hidden from the user's view, set value, add the textarea element to the body.

Select textarea element, then use document.execCommand('copy')  to copy text to the clipboard.

Then remove the textarea element, and set selection and focus back.

Don't expect clipboard-related commands to work while you are testing code in the console. Generally, the page is required to be active or requires user interaction (e.g. a user click) to allow (document.execCommand('copy')) to access the clipboard.

Clipboard API: writeText() Browsers support is at 92%. Check out the latest coverage at Can I use Clipboard API: writeText().

document.execCommand('copy') Browsers support is at 95%. Check out the latest coverage at Can I use Document API: execCommand: copy command.

Clipboard API documentation on MDN

Document.execCommand() documentation on MDN

© 2022 Sino Thomas.