Home About Me

Copying Text to the Clipboard Without the Usual Baggage

Copying a link, a code snippet, or a preset string is a small interaction that users expect to work instantly. clipboard.js handles that job without Flash, heavy setup, or a large dependency. The minified library is about 3KB and lets you attach copy behavior to a button or any other trigger.

Why clipboard.js is worth considering

Clipboard behavior does not need a build step or pages of configuration. clipboard.js removes the old Flash requirement, stays small, and supports modern browsers. It also falls back gracefully on older ones, which matters when the rest of the interface still needs to work for a broad audience.

Installing the library

npm

npm install clipboard --save

ZIP download

If you prefer not to use a package manager, you can download the ZIP file directly.

Loading it on the page

You can load the script from your local dist folder or from a CDN.

Local file

<script src="dist/clipboard.min.js"></script>

CDN

<script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>

Creating an instance

After the script is loaded, pass a DOM selector or an element to ClipboardJS:

new ClipboardJS(".btn");

This attaches copy listeners to every element that matches .btn. The library uses event delegation, so it adds one listener instead of one per button, keeping memory use under control.

Different ways to copy

Copying from another element

A common pattern is to copy content that already exists elsewhere on the page. Add data-clipboard-target to the trigger and point it at the target element's selector.

<!-- Target element -->
<input id="foo" value="https://github.com/zenorocha/clipboard.js.git" />

<!-- Trigger button -->
<button class="btn" data-clipboard-target="#foo">
  <img src="assets/clippy.svg" alt="Copy to clipboard" />
</button>

Clicking the button copies the input's current value to the clipboard.

Cutting text

Copy is the default action, but data-clipboard-action can switch the trigger to cut behavior, similar to Ctrl+X.

<!-- Target element -->
<textarea id="bar">剪切这段文本...</textarea>

<!-- Trigger button -->
<button class="btn" data-clipboard-action="cut" data-clipboard-target="#bar">
  剪切到剪贴板
</button>

Cut only works with <input> and <textarea> elements.

Copying literal text

Sometimes the text does not exist in another element. In that case, put the value in data-clipboard-text on the trigger.

<!-- Trigger button -->
<button class="btn" data-clipboard-text="复制这段文本">复制到剪贴板</button>

Handling events

clipboard.js emits success and error events, so you can show feedback or run additional logic after a copy attempt.

var clipboard = new ClipboardJS(".btn");

clipboard.on("success", function (e) {
  console.log("复制成功:", e.text);
  e.clearSelection();
});

clipboard.on("error", function (e) {
  console.error("复制失败:", e.action);
});

These listeners are useful for status messages, analytics, or any other response to a completed or failed action.

Dynamic values and cleanup

The library can also resolve the text dynamically from the trigger element:

new ClipboardJS(".btn", {
  text: function (trigger) {
    return trigger.getAttribute("data-copy");
  },
});

In applications where elements come and go, such as single-page apps, you may need to remove the listeners yourself:

var clipboard = new ClipboardJS(".btn");
clipboard.destroy();

Browser support

clipboard.js relies on the Selection and execCommand APIs, which are available in all modern browsers. On older browsers it degrades gracefully, often showing a prompt such as Ctrl+C. Supported browser versions include Chrome 42+, Edge 12+, Firefox 41+, Internet Explorer 9+, Opera 29+, and Safari 10+.

Full working example

The page below demonstrates copying from an input, cutting from a textarea, copying a preset string, and displaying success or failure feedback. It can be saved as an HTML file and opened directly.

<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>clipboard.js 示例</title>
    <!-- Include clipboard.js -->
    <script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
    <style>
      body {
        font-family: Arial, sans-serif;
        margin: 50px;
      }
      .container {
        max-width: 600px;
        margin: 0 auto;
        text-align: center;
      }
      button {
        margin-top: 20px;
        padding: 10px 20px;
        font-size: 16px;
        cursor: pointer;
      }
      input,
      textarea {
        width: 100%;
        padding: 10px;
        margin-top: 10px;
      }
      .message {
        color: green;
        margin-top: 10px;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <h1>使用 clipboard.js 复制文本到剪贴板</h1>

      <!-- Input field -->
      <input
        id="copyInput"
        value="https://github.com/zenorocha/clipboard.js.git"
      />

      <!-- Copy button -->
      <button class="btn" data-clipboard-target="#copyInput">复制链接</button>

      <!-- Text area -->
      <textarea id="copyText">复制这段文本...</textarea>

      <!-- Cut button -->
      <button
        class="btn"
        data-clipboard-action="cut"
        data-clipboard-target="#copyText"
      >
        剪切文本
      </button>

      <!-- Copy preset text button -->
      <button class="btn" data-clipboard-text="这是直接复制的文本">
        复制预设文本
      </button>

      <!-- Area for operation result -->
      <div class="message" id="message"></div>
    </div>

    <script>
      // Instantiate ClipboardJS
      var clipboard = new ClipboardJS(".btn");

      // Event handler for successful copy
      clipboard.on("success", function (e) {
        var message = document.getElementById("message");
        message.textContent = "复制成功: " + e.text;
        e.clearSelection(); // Clear selection
      });

      // Event handler for copy failure
      clipboard.on("error", function (e) {
        var message = document.getElementById("message");
        message.textContent = "复制失败,请手动复制!";
      });
    </script>
  </body>
</html>

For a common interface task like this, clipboard.js keeps the markup readable and the JavaScript surface small, which is usually the right trade-off when copying is only one part of a larger page.