How to Create a Copy to Clipboard Function in JavaScript

Copying text to the clipboard is a common requirement in web applications for easily sharing information like links, code snippets, or specific text. This guide will walk you through how to use a JavaScript function to copy text to the clipboard, supporting both modern and older browsers. We’ll explain the code step-by-step, then show you how to integrate it with HTML for a smooth user experience.

The Code: copyToClipboard Function

Here’s the function that does the magic:

/**
 * A function to copy text contents to clipboard
 *
 * @param {string} text The text content to copy
 *
 * @returns {Promise<void>} A Promise which resolves with undefined
 */
function copyToClipboard(text) {
  return new Promise(function (resolve, reject) {
    // checks if argument text is string
    if (typeof text !== "string") {
      reject(new TypeError("Argument 1 must be a string."));
    } else {
      // use clipboard web api if available
      if ("clipboard" in navigator) {
        navigator.clipboard.writeText(text).then(resolve).catch(reject);
      } else {
        var textarea = document.createElement("textarea");
        textarea.setAttribute(
          "style",
          "position: fixed; top: -100%; left: -100%; width: 0; height: 0; opacity: 0"
        );
        textarea.textContent = text;

        document.body.appendChild(textarea);
        textarea.focus();
        textarea.select();

        var isCopied = !!document.execCommand("copy");
        textarea.remove();

        if (isCopied) {
          resolve(undefined);
        } else {
          reject(new Error("Failed to copy text."));
        }
      }
    }
  });
}

How It Works: Step-by-Step Explanation

Let’s break down how the copyToClipboard function works.

  1. Input Validation: The function first checks if the argument text is a valid string. If it isn’t, the promise is rejected with a TypeError.
    if (typeof text !== "string") {
      reject(new TypeError("Argument 1 must be a string."));
    }
  2. Modern Clipboard API: If the browser supports the modern Clipboard API (navigator.clipboard.writeText), the function uses it to write the text to the clipboard. It returns a promise that resolves on success and rejects on failure.
    if ("clipboard" in navigator) {
      navigator.clipboard.writeText(text).then(resolve).catch(reject);
    }
  3. Fallback for Older Browsers: If the browser does not support the Clipboard API, the function creates a hidden <textarea> element. This is because older browsers (like Internet Explorer) only allow copying text from input elements or textareas.
    • The textarea is created off-screen using CSS and its textContent is set to the text to be copied.
    • The textarea is appended to the body, focused, and selected so that the text is highlighted.
    var textarea = document.createElement("textarea");
    textarea.setAttribute(
    "style",
    "position: fixed; top: -100%; left: -100%; width: 0; height: 0; opacity: 0"
    );
    textarea.textContent = text;
  4. Copying Text: After selecting the text, the function attempts to copy it using the document.execCommand("copy") method. This is an older method supported by browsers that don’t have the Clipboard API.
    const isCopied = !!document.execCommand("copy");
    textarea.remove();
    • If the text was successfully copied, the function resolves the promise.If it wasn’t, it rejects the promise with an error.
    if (isCopied) {
    resolve(undefined);
    } else {
    reject(new Error("Failed to copy text."));
    }

Example Usage: HTML and JavaScript

Now that you understand how the function works, let’s look at an example where we integrate this into a simple web page.

HTML Structure

In this example, we will create a paragraph with some text and a button that, when clicked, will copy the text to the clipboard.

<div>
  <p id="copy-text">This is the text that will be copied to the clipboard when you click the button below.</p>
  <button id="copy-button">Copy Text</button>
</div>

JavaScript for Copying

Here’s how you use the copyToClipboard function to copy the text from the paragraph when the button is clicked.

// Select the elements
var copyButton = document.getElementById("copy-button");
var textToCopy = document.getElementById("copy-text").innerText;

// Add click event to the button
copyButton.addEventListener("click", function () {
  copyToClipboard(textToCopy)
    .then(function () {
      alert("Text copied to clipboard!");
    })
    .catch(function (err) {
      console.error("Failed to copy text: ", err);
    });
});

Full Example: HTML + JavaScript Combined

Here’s the complete code for your webpage, integrating the copyToClipboard function with an HTML button:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Copy to Clipboard Example</title>
</head>

<body>
  <div>
    <p id="copy-text">This is the text that will be copied to the clipboard when you click the button below.</p>
    <button id="copy-button">Copy Text</button>
  </div>

  <script>
    /**
     * A function to copy text contents to clipboard
     *
     * @param {string} text The text content to copy
     *
     * @returns {Promise<void>} A Promise which resolves with undefined
     */
    function copyToClipboard(text) {
      return new Promise(function (resolve, reject) {
        // checks if argument text is string
        if (typeof text !== "string") {
          reject(new TypeError("Argument 1 must be a string."));
        } else {
          // use clipboard web api if available
          if ("clipboard" in navigator) {
            navigator.clipboard.writeText(text).then(resolve).catch(reject);
          } else {
            var textarea = document.createElement("textarea");
            textarea.setAttribute(
              "style",
              "position: fixed; top: -100%; left: -100%; width: 0; height: 0; opacity: 0"
            );
            textarea.textContent = text;

            document.body.appendChild(textarea);
            textarea.focus();
            textarea.select();

            var isCopied = !!document.execCommand("copy");
            textarea.remove();

            if (isCopied) {
              resolve(undefined);
            } else {
              reject(new Error("Failed to copy text."));
            }
          }
        }
      });
    }

    // Select the elements
    var copyButton = document.getElementById("copy-button");
    var textToCopy = document.getElementById("copy-text").innerText;

    // Add click event to the button
    copyButton.addEventListener("click", function () {
      copyToClipboard(textToCopy)
        .then(function () {
          alert("Text copied to clipboard!");
        })
        .catch(function (err) {
          console.error("Failed to copy text: ", err);
        });
    });
  </script>
</body>

</html>

Summary

The copyToClipboard function is a simple yet powerful tool for copying text to the clipboard in web applications. It handles both modern browsers (via the Clipboard API) and older browsers (via the document.execCommand method). By using this function, you can easily add clipboard copy functionality to your websites with minimal code.

With this approach, users can copy content, such as text or links, with just a click of a button, improving the user experience on your site.

Share your love
Dev Kumar
Dev Kumar

Dev Kumar is a tech enthusiast and content creator specializing in coding tutorials and technical guides. As a key contributor to BytesAndBucks.com, he shares insights and hands-on tutorials aimed at helping users enhance their coding skills and navigate the tech landscape.

Articles: 1

Leave a Reply

Your email address will not be published. Required fields are marked *