clipboard.js

repository·master·Indexed 12 days ago

https://github.com/zenorocha/clipboard.js

A lightweight JavaScript library (version 2.0.11) for modern copy-to-clipboard functionality. It provides a declarative approach using HTML5 data attributes or an imperative API to manage copy and cut actions without relying on Flash.

Tokens
2.6K
Snippets
14
Records
14
Agent score
49%

What's inside clipboard.js

  1. Initialize clipboard.js

    master

    After including the script in your project, instantiate ClipboardJS by passing a DOM selector, an HTML element, or a list of HTML elements. The library uses event delegation to efficiently attach listeners to all matching elements.

    // Using a selector
    new ClipboardJS('.btn');
    new ClipboardJS('.btn');
  2. Copy text from another element

    master

    To copy content from a different element, add the data-clipboard-target attribute to your trigger element. The value must be a valid CSS selector for the target element.

    <!-- Target -->
    <input id="foo" value="https://github.com/zenorocha/clipboard.js.git" />
    
    <!-- Trigger -->
    <button class="btn" data-clipboard-target="#foo">
      <img src="assets/clippy.svg" alt="Copy to clipboard" />
    </button>
  3. Copy text from an attribute

    master

    To copy text directly from the trigger element without needing a separate target element, use the data-clipboard-text attribute.

    <button
      class="btn"
      data-clipboard-text="Just because you can doesn't mean you should — clipboard.js"
    >
      Copy to clipboard
    </button>
  4. Cut text from another element

    master

    You can specify the action as copy or cut using the data-clipboard-action attribute. If omitted, copy is the default. Note that the cut action only works on <input> or <textarea> elements.

    <!-- Target -->
    <textarea id="bar">Mussum ipsum cacilds...</textarea>
    
    <!-- Trigger -->
    <button class="btn" data-clipboard-action="cut" data-clipboard-target="#bar">
      Cut to clipboard
    </button>
  5. Configure clipboard.js via options object

    master

    If you prefer not to use HTML data attributes, you can use the imperative API by passing an options object to the constructor.

    Options:

    • target: A function that returns a DOM Node (the target element).
    • text: A function that returns a String (the text to copy).
    • container: A DOM Node that acts as the container for the operation (useful for Bootstrap Modals or libraries that change focus).
    // Dynamic target
    new ClipboardJS('.btn', {
      target: function (trigger) {
        return trigger.nextElementSibling;
      },
    });
    
    // Dynamic text
    new ClipboardJS('.btn', {
      text: function (trigger) {
        return trigger.getAttribute('aria-label');
      },
    });
    
    // Setting a container for focus management
    new ClipboardJS('.btn', {
      container: document.getElementById('modal'),
    });
    new ClipboardJS('.btn', {
      target: function (trigger) {
        return trigger.nextElementSibling;
      },
    });
  6. Handle success and error events

    master

    Clipboard.js fires success and error events. You can listen to these to provide user feedback (like tooltips) or capture metadata about the operation.

    Event Object Properties:

    • e.action: The action performed (copy or cut).
    • e.text: The text that was copied/cut (only available on success).
    • e.trigger: The element that triggered the event.
    var clipboard = new ClipboardJS('.btn');
    
    clipboard.on('success', function (e) {
      console.info('Action:', e.action);
      console.info('Text:', e.text);
      console.info('Trigger:', e.trigger);
    
      // Clears the text selection from the target element
      e.clearSelection();
    });
    
    clipboard.on('error', function (e) {
      console.error('Action:', e.action);
      console.error('Trigger:', e.trigger);
    });
    var clipboard = new ClipboardJS('.btn');
    
    clipboard.on('success', function (e) {
      console.info('Action:', e.action);
      console.info('Text:', e.text);
      console.info('Trigger:', e.trigger);
    
      e.clearSelection();
    });
    
    clipboard.on('error', function (e) {
      console.error('Action:', e.action);
      console.error('Trigger:', e.trigger);
    });
  7. Check browser support

    master

    Clipboard.js relies on the Selection and execCommand APIs. You can check if the current environment supports the library using ClipboardJS.isSupported(). This is useful for hiding copy/cut buttons in unsupported browsers.

    if (ClipboardJS.isSupported()) {
      // Initialize clipboard
    } else {
      // Hide buttons or show fallback instructions
    }
    ClipboardJS.isSupported();
  8. Destroy a ClipboardJS instance

    master

    In Single Page Applications (SPAs), you should clean up event listeners and objects when a component unmounts to prevent memory leaks.

    var clipboard = new ClipboardJS('.btn');
    // ... later
    clipboard.destroy();
    var clipboard = new ClipboardJS('.btn');
    clipboard.destroy();
  9. Configure Clipboard options

    master

    When instantiating new Clipboard(trigger, options), you can provide an options object to override the default lookup behaviors for actions, targets, and text. You can pass either a static value or a function that receives the trigger element as an argument.

    Supported option keys:

    • action: A function or string defining the operation (e.g., 'copy' or 'cut'). Defaults to looking up data-clipboard-action on the trigger.
    • target: A function or selector string defining where the content comes from. Defaults to looking up data-clipboard-target on the trigger.
    • text: A function or string defining the text to copy. Defaults to looking up data-clipboard-text on the trigger.
    • container: The DOM element used as a container for the clipboard operation. Defaults to document.body.
    const clipboard = new Clipboard('.btn', {
      // Use a function to dynamically determine text
      text: (trigger) => trigger.getAttribute('custom-text'),
      
      // Use a function to dynamically determine the target element
      target: (trigger) => document.querySelector('#target-element'),
      
      // Specify a custom container
      container: document.querySelector('.modal-body'),
      
      // Specify a custom action
      action: (trigger) => trigger.dataset.action || 'copy'
    });
  10. Instantiate Clipboard with the Clipboard class

    master

    The Clipboard class is the main entrypoint for attaching clipboard functionality to elements. You can instantiate it by passing a trigger (a CSS selector string, an HTMLElement, an HTMLCollection, or a NodeList) and an optional options object.

    When a click event occurs on the trigger, the class resolves the action (copy/cut), the target content, and the text to be used, then executes the operation.

    To prevent memory leaks, call the .destroy() method when the clipboard instance is no longer needed to remove event listeners.

    import Clipboard from 'clipboard.js';
    
    // Using a CSS selector
    const clipboard = new Clipboard('.btn-copy');
    
    // Using a specific element
    const element = document.querySelector('#my-button');
    const clipboard = new Clipboard(element, {
      container: document.body
    });
    
    // Cleanup
    clipboard.destroy();
  11. Perform programmatic copy and cut actions

    master

    You can trigger clipboard operations directly without waiting for a click event using the static copy and cut methods on the Clipboard class.

    import Clipboard from 'clipboard.js';
    
    // Programmatic copy
    // target can be an HTMLElement or a string selector
    Clipboard.copy('#target-element', { container: document.body });
    
    // Programmatic cut
    Clipboard.cut('#target-element');