How to copy text to the clipboard using Javascript?

Allowing a user to copy text by clicking a button is a common pattern in websites. Let’s see how to copy text to clipboard using Javascript

Copy using the navigator.clipboard API

Here’s how to copy or set some text to the clipboard:

navigator.clipboard.writeText("Some text to be copied");

Full source code

Here’s the full source code and live demo


<!DOCTYPE html>
<html lang="en">
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
      href="data:image/svg+xml,<svg xmlns=%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>🎉</text></svg>"
    <title>How to copy text</title>
    <h1>How to copy text</h1>
    <textarea rows="3">
Some sample text for you to copy. Feel free to edit this.</textarea
    <button type="button">Copy</button>


const textarea = document.querySelector('textarea');
const button = document.querySelector('button');

button.addEventListener('click', async () => {
  try {
    await navigator.clipboard.writeText(textarea.value);
  } catch (err) {
    console.error(, err.message);

Live Demo

See the Pen Copy text to clipboard by Ranjith (@Ranjithkumar10) on CodePen.

Ranjith kumar
0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments