joshmoto
joshmoto

Reputation: 5128

clipboardjs copy the html contents of a div to the clipboard

I trying copy the html contents of multiple divs using zenorocha clipboardjs javascript plugin. Please don't post other alternatives as I would like give this plugin a go, as it seems solid on the browsers that I want to cover.

I've looked at this issue on zenorocha's github, but this code just seems to return an Uncaught TypeError: Illegal constructor.

new Clipboard('.copy', {
    text: function() {
        var htmlBlock = document.querySelector('.yourSelector');
        return htmlBlock.innerHTML;
    }
});

I've created an example fiddle if anyone can help me use clipboardjs to copy the html content of a div.

JS

// copy to clipboard
new Clipboard('.copy');

HTML

<div id="content_1">
   <div><b>Heading Post 1</b></div>
   <div>Blah, blah, blah</div>
</div>

<button class="copy" data-copy-element="content_1">
   Copy to clipboard
</button>

I've made up a new data attribute called data-copy-element as there will be multiple buttons and content blocks on a single page.

See fiddle here https://jsfiddle.net/joshmoto/qLord78p/

Is this actually possible using zenorocha clipboardjs?

Thanks in advance.

Upvotes: 0

Views: 2185

Answers (2)

joshmoto
joshmoto

Reputation: 5128

Here is my final code, I used a bit of jQuery to get the specific element related to the copy button.

JS

new ClipboardJS('.copy', {
    text: function(trigger) {
        elem = $(trigger).data('clipboard-element');
        var htmlBlock = document.querySelector(elem);
        return htmlBlock.innerHTML;
    }
});

HTML

<div id="content_1">
   <div><b>Heading Post 1</b></div>
   <div>Blah, blah, blah</div>
</div>

<button class="copy" data-clipboard-element="#content_1">
   Copy to clipboard
</button>

See fiddle: https://jsfiddle.net/joshmoto/j2masp3u/

Upvotes: 0

cwallenpoole
cwallenpoole

Reputation: 82078

Clipboard is a native class, accessible through (among other places) Chrome's Clipboard API.

If you want to get that code to work, change Clipboard to ClipboardJS. In fact, that's even how ClipboardJS documentation calls it. This works just fine:

new ClipboardJS('.copy', {
    text: function() {
        // based on your fiddle, you may need to replace this selector, too.
        var htmlBlock = document.querySelector('.yourSelector');
        return htmlBlock.innerHTML;
    }
});

Upvotes: 3

Related Questions