javascriptclipboard

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.


Solution

  • 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;
        }
    });