Clipboard.js - Documentation

Introduction

What is Clipboard.js?

Clipboard.js is a small, lightweight JavaScript library for copying text to the clipboard. It provides a simple and cross-browser way to implement copy-to-clipboard functionality without requiring complex code or server-side assistance. Instead of relying on Flash or other browser plugins, it utilizes the browser’s native clipboard APIs (where available) for optimal performance and security. Fallback mechanisms are implemented for browsers lacking direct clipboard support.

Why use Clipboard.js?

Using Clipboard.js offers several advantages:

Browser Compatibility

Clipboard.js aims for broad browser compatibility. While it strives to support as many browsers as possible using fallback mechanisms, optimal functionality relies on modern browser features. For the most reliable experience, we recommend using current versions of the following:

Older browsers or those with disabled clipboard APIs may have limitations in functionality. Specific compatibility details may vary based on the version of Clipboard.js and the user’s browser configuration.

Getting Started

To use Clipboard.js, first include the library in your project. You can download the minified version from [https://clipboardjs.com/] or use a CDN like unpkg:

<script src="https://unpkg.com/clipboard@2/dist/clipboard.min.js"></script> </html>

Next, instantiate a new Clipboard object, targeting the element you want to attach the copy functionality to. This element usually has a data attribute indicating the text to copy:

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

Here, '.btn' selects all elements with the class “btn”. Each of these elements should have a data-clipboard-text attribute specifying the text to be copied:

<button class="btn" data-clipboard-text="Copy this text!">Copy</button>

Clipboard.js will automatically handle the copying process when the selected element is clicked. You can optionally add event listeners for success or error callbacks:

var clipboard = new ClipboardJS('.btn', {
  success: function(e) {
    console.log(e.text); // The text that was copied
    console.log(e.trigger); // The element that was clicked
    alert("Text copied!");
  },
  error: function(e) {
    console.error('Action:', e.action);
    console.error('Trigger:', e.trigger);
    console.error('Message:', e.text);
    alert("Failed to copy!");
  }
});

Remember to remove the event listener if needed to prevent memory leaks:

clipboard.destroy();

Basic Usage

Including Clipboard.js

There are several ways to include Clipboard.js in your project:

<script src="path/to/clipboard.min.js"></script>

Replace "path/to/clipboard.min.js" with the actual path to the downloaded file.

<script src="https://unpkg.com/clipboard@2/dist/clipboard.min.js"></script>

This method is convenient as you don’t need to manage the file yourself. Ensure the CDN link is correct and that the version number (@2 in this example) matches the documentation.

Creating a Copy Button

Create a button element in your HTML. This button will trigger the copy action. It’s crucial to include the data-clipboard-text attribute, which specifies the text to be copied to the clipboard. The text can be any valid string, including HTML entities if desired.

<button class="btn" data-clipboard-text="This text will be copied!">Copy</button>

Targeting Elements

Clipboard.js uses the CSS selector you provide to find the elements to attach the copy functionality to. The selector can be a class (as above), an ID, or any valid CSS selector. Multiple elements matching the selector will all have copy functionality applied. Each element must have a data-clipboard-text attribute to define what text will be copied when it’s clicked. You can target multiple buttons with different content. If a single element is matched, only that element will have the copy event listener applied.

<button class="btn" data-clipboard-text="Text 1">Copy 1</button>
<button id="myButton" data-clipboard-text="Text 2">Copy 2</button>
<button class="btn" data-clipboard-text="Text 3">Copy 3</button>

Basic Copy Example

This example combines the inclusion of Clipboard.js, the creation of a button, and the instantiation of the ClipboardJS object:

<!DOCTYPE html>
<html>
<head>
<title>Clipboard.js Example</title>
<script src="https://unpkg.com/clipboard@2/dist/clipboard.min.js"></script>
</head>
<body>

<button class="btn" data-clipboard-text="Hello, world!">Copy Text</button>

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

</body>
</html>

This code will create a button. When clicked, the text “Hello, world!” will be copied to the clipboard. No additional JavaScript is needed for this basic functionality beyond the instantiation of ClipboardJS. Remember to replace the CDN link with your local path if you downloaded the library.

Advanced Usage

Customizing Button Text

By default, Clipboard.js doesn’t change the button’s text. To dynamically update button text after a copy action, use the success and error callbacks (described below) to modify the button’s innerHTML or textContent. For example:

var clipboard = new ClipboardJS('.btn', {
  success: function(e) {
    e.trigger.textContent = 'Copied!';
  },
  error: function(e) {
    e.trigger.textContent = 'Copy failed!';
  }
});

This code changes the button text to “Copied!” on success and “Copy failed!” on error. Remember that directly manipulating the DOM within these callbacks ensures the changes reflect the copy action’s outcome.

Handling Success and Error

The success and error callback functions within the ClipboardJS options object allow you to handle the outcome of the copy operation. The success callback receives an object with text (the copied text) and trigger (the clicked element) properties. The error callback provides information about the failure, including the action attempted, the trigger element, and an optional text message.

var clipboard = new ClipboardJS('.btn', {
  success: function(e) {
    console.log('Copied:', e.text); // Log the copied text to the console
    alert('Text copied to clipboard!'); //Show an alert message.
  },
  error: function(e) {
    console.error('Clipboard action failed:', e); // Log error details
    alert('Failed to copy text to clipboard!'); //Show an alert message
  }
});

Text Selection

Clipboard.js copies the text specified in the data-clipboard-text attribute. It does not copy selected text from the page. If you want to copy selected text, you’ll need to implement that functionality separately, possibly using the window.getSelection() method and setting the data-clipboard-text attribute dynamically based on the selected text.

Copying HTML

While data-clipboard-text accepts HTML, it’s typically interpreted as plain text. To copy HTML as formatted HTML (not rendered HTML), you’ll need to escape special characters appropriately before assigning them to the data-clipboard-text attribute. Consider using a library or function to properly escape HTML entities to prevent injection vulnerabilities.

Asynchronous Copying

Clipboard.js primarily operates synchronously. However, if you need to perform actions before copying (like dynamically generating the text), you might need to incorporate asynchronous operations, ensuring the data-clipboard-text is updated before the user interacts with the button:

//Simulate Async Data Retrieval
function getAsyncText() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve("This is the async text!");
    }, 1000); // Simulate a delay
  });
}

getAsyncText().then((text) => {
  const btn = document.querySelector('.btn');
  btn.setAttribute('data-clipboard-text', text);
  new ClipboardJS('.btn');
})

Multiple Copy Buttons

You can target multiple copy buttons by using a CSS selector that matches all of them. Each button should have its own data-clipboard-text attribute specifying the text it should copy:

<button class="copy-button" data-clipboard-text="Text 1">Copy 1</button>
<button class="copy-button" data-clipboard-text="Text 2">Copy 2</button>
<script>
  var clipboard = new ClipboardJS('.copy-button');
</script>

Using with Frameworks (React, Vue, Angular, etc.)

Clipboard.js is a plain JavaScript library, and it can be used in any JavaScript framework. The integration approach depends on the framework. Common methods include:

Remember to handle potential lifecycle issues (like unmounting components) and to appropriately manage the Clipboard.js instance to avoid memory leaks, particularly in frameworks with component lifecycles. Consult your framework’s documentation for guidance on integrating external libraries.

Options and Configuration

The clipboard Object

The core of Clipboard.js functionality revolves around the ClipboardJS object. You create an instance of this object, passing in options to customize its behavior. The options are passed as a single object to the constructor:

const clipboard = new ClipboardJS(selector, options);

Where selector is a CSS selector string targeting the elements to which you’ll attach copy functionality, and options is an object detailing the configuration.

The target Option

The target option specifies the element whose content should be copied. It is particularly useful when you want to copy text from an element other than the one that triggered the copy action (e.g., copying text from a hidden element when a button is clicked). The value should be a CSS selector string targeting the element containing the text to be copied. If not provided, the text will be pulled from the data-clipboard-text attribute of the trigger element.

const clipboard = new ClipboardJS('.copy-button', {
  target: '#hidden-text'
});

In this example, clicking an element with the class copy-button will copy the text content of the element with the ID hidden-text.

The text Option

The text option provides a function that dynamically generates the text to be copied. This function receives the trigger element as an argument and should return a string. This is especially useful when the text to copy depends on data not directly present in the HTML.

const clipboard = new ClipboardJS('.copy-button', {
  text: function(trigger) {
    return trigger.dataset.customText || 'Default text';
  }
});

Here, the function checks for a data-custom-text attribute on the trigger element; if present, it uses that value; otherwise, it uses “Default text”.

The action Option

The action option is less frequently used but allows you to specify the copy action to perform. The default is ‘copy’. While other actions might be supported by browsers (like ‘cut’), it’s typically not necessary to explicitly set it.

// Usually not needed, default is 'copy'
const clipboard = new ClipboardJS('.copy-button', {
  action: 'copy'
});

The container Option

The container option specifies a parent element within which to search for the target element if using the target option. If not specified, Clipboard.js searches the entire document. This is useful for optimizing performance when dealing with large documents.

const clipboard = new ClipboardJS('.copy-button', {
  target: '.target-element',
  container: '#my-container'
});

This limits the search for .target-element to only within the element having the ID my-container.

The trigger Option

The trigger option allows you to manually set the element that should trigger the copy action. While the constructor’s first argument implicitly sets the trigger, this option provides explicit control. It’s less commonly needed unless advanced scenarios require decoupling the trigger element from the target element beyond what target alone can achieve.

The debug Option

The debug option enables verbose logging to the console for debugging purposes. Setting debug to true will output detailed information about the copy process, which can be helpful for troubleshooting issues.

const clipboard = new ClipboardJS('.copy-button', {
  debug: true
});

This will print useful information in your browser’s console for analysis during development. Remember to disable this option in production.

Events and Callbacks

Clipboard.js provides two main events/callbacks that allow you to respond to the success or failure of a copy operation: success and error. These are configured within the options object passed to the ClipboardJS constructor.

success Event

The success callback function is executed when the copy operation is successful. It receives a single argument: an object containing information about the successful copy action.

error Event

The error callback function is executed when the copy operation fails. This can happen for various reasons, including browser limitations or user permissions. The event object passed to the callback contains:

Event Handling Examples

Here are examples demonstrating how to use the success and error events:

Example 1: Basic Success/Error Handling

const clipboard = new ClipboardJS('.btn', {
  success: function(e) {
    console.log('Copied text: ', e.text);
    alert('Text copied to clipboard!');
  },
  error: function(e) {
    console.error('Copy failed: ', e);
    alert('Failed to copy text. Please try again.');
  }
});

Example 2: Updating Button Text

const clipboard = new ClipboardJS('.btn', {
  success: function(e) {
    e.trigger.textContent = 'Copied!';
  },
  error: function(e) {
    e.trigger.textContent = 'Copy failed!';
  }
});

This example modifies the button’s text after a successful or failed copy attempt.

Example 3: More Detailed Error Handling

const clipboard = new ClipboardJS('.btn', {
    success: function(e) {
      console.log('Copied:', e.text);
    },
    error: function(e) {
      console.error('Action:', e.action);
      console.error('Trigger:', e.trigger);
      if (e.reason) {
        console.error('Reason:', e.reason);
        alert(`Copy failed: ${e.reason}`);
      } else {
        console.error('An unknown error occurred.');
        alert('Copy failed. Please check your browser settings and try again.');
      }
    }
  });

This example provides more informative error messages to the user by checking for the e.reason property. Remember that not all error conditions will necessarily populate the reason field. Handle cases where e.reason is missing to prevent unexpected behavior.

Troubleshooting

Common Errors and Solutions

Error: “Failed to copy: Not allowed to access clipboard” or similar permission errors.

Solution: This usually indicates a browser security restriction. Ensure that the website is served over HTTPS (HTTP is typically blocked for clipboard access). Also, check browser settings related to clipboard access permissions. The user may need to explicitly allow the website access to the clipboard. Some browser extensions may also interfere with clipboard access. Try disabling such extensions temporarily for testing purposes.

Error: The copy action doesn’t seem to work at all, no errors in the console.

Solution:

Error: Uncaught TypeError: Cannot read properties of undefined (reading 'trigger') or similar errors related to e.trigger being undefined.

Solution: This error often arises if you access e.trigger outside the scope of the success or error callbacks. These callbacks provide e.trigger only within their context. Ensure that you’re only accessing e.trigger inside these handlers.

Error: The copied text is incorrect or incomplete.

Solution: Verify the content of the data-clipboard-text attribute or the text returned from the text option function. Ensure you are not accidentally copying HTML entities that are not properly escaped.

Debugging Tips

Browser-Specific Issues

While Clipboard.js strives for cross-browser compatibility, minor inconsistencies can occur. Here are some browser-specific considerations:

If you encounter problems not addressed here, provide a minimal reproducible example, including your code and the browser details, when seeking support. This greatly aids in diagnosing and resolving the issue.

API Reference

Clipboard.js provides a few methods on the instantiated clipboard object for advanced control and management of the copy functionality.

clipboard.on(eventName, callback)

This method adds an event listener to the Clipboard.js instance. It allows you to listen for custom events beyond the built-in success and error callbacks. While Clipboard.js doesn’t trigger many custom events directly, this method can be useful for integrating with other libraries or for extending functionality.

Example: (Illustrative, as Clipboard.js itself doesn’t directly trigger myCustomEvent)

const clipboard = new ClipboardJS('.btn');

clipboard.on('myCustomEvent', (event) => {
  console.log('Custom event triggered:', event);
});

// You would trigger 'myCustomEvent' from your application logic separately.

clipboard.off(eventName, callback)

This method removes an event listener that was previously added using clipboard.on(). If you add multiple listeners for the same event, this will remove only the specific listener callback function provided.

Example:

const myCustomCallback = (event) => { /* ... */ };
clipboard.on('myCustomEvent', myCustomCallback);
// ... later ...
clipboard.off('myCustomEvent', myCustomCallback); // Removes only myCustomCallback
clipboard.off('myCustomEvent'); // Removes all listeners for 'myCustomEvent'

clipboard.destroy()

This method completely destroys the Clipboard.js instance, removing all event listeners and releasing any resources it holds. It’s crucial to call this method when you no longer need the Clipboard.js functionality, especially in applications with component lifecycles (like React or Vue), to prevent memory leaks and potential conflicts. Failing to destroy the instance can lead to unexpected behavior or errors.

Example:

const clipboard = new ClipboardJS('.btn');
// ... later, when you no longer need the clipboard functionality ...
clipboard.destroy();

In frameworks like React, you would typically call destroy() within the componentWillUnmount lifecycle method to ensure cleanup when the component is removed from the DOM. In Vue, you might place it within the beforeDestroy hook. Always follow the best practices of your specific framework to effectively manage the lifecycle of external libraries.

Contributing

We welcome contributions to Clipboard.js! Whether it’s reporting bugs, suggesting improvements, or submitting code changes, your involvement helps make the library better for everyone.

Reporting Issues

When reporting an issue, please provide as much detail as possible to help us understand and reproduce the problem. A minimal, reproducible example is particularly valuable. Here’s what to include:

Submitting Pull Requests

Before submitting a pull request (PR), please ensure:

Coding Style Guide

Clipboard.js follows a consistent coding style to ensure readability and maintainability. Please adhere to these guidelines when submitting pull requests:

By following these guidelines, you ensure that your contributions are easily integrated into the project and maintain the overall quality of Clipboard.js. If you have any questions about the contribution process or coding style, feel free to open an issue or contact the maintainers.

License

License Information

Clipboard.js is licensed under the MIT License. This means you are free to use, modify, and distribute Clipboard.js in your projects, both commercial and non-commercial, as long as you include the original copyright and license notice in your distribution.

The full text of the MIT License is as follows:

MIT License

Copyright (c) 2017-present Zeno Rocha

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

For clarification on the terms of the MIT License, you should consult a legal professional. This information is provided for convenience and should not be considered legal advice.