Search code examples
javascriptjqueryclipboardzeroclipboardclipboard.js

How to copy using clipboard.js with dynamic content and triggers


After a click on .fw-code-copy-button I would like to copy source code from it's nearest container. .fw-code-copy-button-s are created dynamically, after user click dedicated "view source" button.

Html for example button:

<span class="fw-code-copy">
  <span class="fw-code-copy-button" data-clipboard-text="...">copy</span>
</span>

This is how i trigger click event, and define the source code to be copied to clipboard:

$(document).on("click", ".fw-code-copy-button", function(){
  var source = $(this).closest(".fw-code-copy").next("code").text();
});

And this is how clipboard.js triggers it's copy event

new Clipboard(".fw-code-copy-button", {
  text: function(trigger) {
    return source; // source should somehow be copied from scope above it
  }
});

Whenever i click anywhere on the website, the following error appears:

Uncaught Error: Missing required attributes, use either "target" or "text"

But first of all I don't want to define text to be copied in data-clipboard-text="..." and secondly data-clipboard-text is defined with "..." as it's value.

If someone would pay a second i would be very grateful.

[edit] I have written jsFiddle for demonstration, and suprisingly UncaughtError disappeared, but i still need to move source code from onClick to Clipboard scope.

https://jsfiddle.net/2rjbtg0c/1/


Solution

  • According to your original code:

     new Clipboard(".fw-code-copy-button", {
      text: function(trigger) {
        return $(trigger).closest(".fw-code-copy").next("code").text(); 
      }
    });