0

I am wondering how to use the Clipboard.js functionality when dynamically adding content using jQuery. Currently my code is as follows which works if static on a page loaded without jQuery:

<div class="snippet"><div id="title">TEXT TO COPY</div></div>

When I load this as a dynamic addition using jQuery I am doing the following which doesn't work:

var content = '<div class="snippet"><div id="title">TEXT TO COPY</div></div>';
$('#profilesTable').append(content);

I have tried:

new Clipboard('.snippet');

after loading the content but that doesn't work, as well as what was mentioned on the Clipborad.js page for advanced usage:

new Clipboard('.snippet', {
    target: function(trigger) {
        return trigger.nextElementSibling;
    }
});

This doesn't seem to work either. What am I missing after I dynamically add my content?

I have looked at Understanding non-functioning Clipboard.js implementation with AJAX but this does not provide the answer.

Thanks

Community
  • 1
  • 1

2 Answers2

1

Thanks for the info all,

My actual issue was due to not using a button, I wanted to use the same hover tooltip option that is displayed on the copy site within the div's. So what I had to do was load the jQuery in every javascript file I was using by calling the function:

    var getSnippets = function() {
    var a = document.querySelectorAll(".snippet");
    [].forEach.call(a, function(a) {
        a.firstChild.insertAdjacentHTML("beforebegin", '<button class="btn copy" data-clipboard-snippet><img class="clippy" width="15" src="scripts/plugins/copy/clippy.svg" alt="Copy to clipboard"></button>')
    });
    var b = new Clipboard("[data-clipboard-snippet]", {
        target: function(a) {
            return a.nextElementSibling
        }
    });
    b.on("success", function(a) {
        a.clearSelection(), showTooltip(a.trigger, "Copied!")
    }), b.on("error", function(a) {
        showTooltip(a.trigger, fallbackMessage(a.action))
    })
};
0

I got this working with dynamically added content, maybe it gives you some insight into solving your exact implementation issue? Basically when I click on the button, it copies the text to the clipboard.

var body = $('body');
var content = '<div class="snippet"><div id="title">TEXT TO COPY</div></div>';
var btn = '<button class="btn" id="snipButton" data-clipboard-target="#title">Copy to clipboard</button>';
body.append(content);
body.append(btn);
var clipboard = new Clipboard('#snipButton');

Here's a link to the jsbin: http://jsbin.com/jukigakafu/edit?html,js,console,output

Robin Chow
  • 79
  • 3