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

After clicking on, .fw-code-copy-buttonI would like to copy the source code from the nearest container. .fw-code-copy-button-s are created dynamically after the user clicks the selected "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 fire the click event and determine the source code to copy to the 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 fires a 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 do not want to define the text to copy in data-clipboard-text="..." and secondly, it data-clipboard-textis defined as "..."a value.

If someone pays a second, I would be very grateful.

[edit] jsFiddle , , UncaughtError , source onClick .

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

+4
2

:

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

- , . . .

Demo

,

new Clipboard(".fw-code-copy-button", {
  text: function(trigger) {
    return $(trigger).parent().find('code').first().text().trim();
  }
});
.fw-code-copy {
  display: block;
  position: relative;
  width: 400px;
  height: 30px;
  background: #FFE;
  border: thin solid #FF0;
  margin-bottom: 0.5em;
  padding: 0.5em;
}
.fw-code-copy-button {
  position: absolute;
  top: 8px;
  right: 8px;
  padding: 0.25em;
  border: thin solid #777;
  background: #800080;
  color: #FFF;
}
.fw-code-copy-button:hover {
  border: thin solid #DDD;
  background: #992699;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/1.5.3/clipboard.min.js"></script>

<span class="fw-code-copy">
  <span class="fw-code-copy-button">Copy</span>
  <code>&lt;link rel=&quot;stylesheet&quot; href=&quot;style-1.css&quot;&gt;</code>
</span>
<span class="fw-code-copy">
  <span class="fw-code-copy-button">Copy</span>
  <code>&lt;link rel=&quot;stylesheet&quot; href=&quot;style-2.css&quot;&gt;</code>
</span>
<span class="fw-code-copy">
  <span class="fw-code-copy-button">Copy</span>
  <code>&lt;link rel=&quot;stylesheet&quot; href=&quot;style-3.css&quot;&gt;</code>
</span>
Hide result
+6

Source: https://habr.com/ru/post/1616220/


All Articles