Prism.js copy to clipboard

Asked by At

I am using Prism JS. I have to implement a copy to clipboard functionality. I found a solution in http://dev.misterphilip.com/prism/plugins/toolbar/.

I tried to implement this solution on my local system using the supporting JS files from this site by doing a view source. But this is not working on my local system.

Thanks for any help.

Regards

1 Answers

2
Imaginaerum On

You can use clipboardjs instead

Download it: https://zenorocha.github.io/clipboard.js/

You can use this method now: (require jquery)

In your html head add:

<script src="dist/clipboard.min.js"></script>

In your html code add:

<pre class="copytoclipboard">
    <code class="language-html">
        <h1>Hello world !</h1>
    </code>
</pre>

In your page footer add:

<script>
        /* Prism copy to clipbaord for all pre with copytoclipboard class */
        $('pre.copytoclipboard').each(function () {
            $this = $(this);
            $button = $('<button>Copy</button>');
            $this.wrap('<div/>').removeClass('copytoclipboard');
            $wrapper = $this.parent();
            $wrapper.addClass('copytoclipboard-wrapper').css({position: 'relative'})
            $button.css({position: 'absolute', top: 10, right: 10}).appendTo($wrapper).addClass('copytoclipboard btn btn-default');
            /* */
            var copyCode = new Clipboard('button.copytoclipboard', {
                target: function (trigger) {
                    return trigger.previousElementSibling;
                }
            });
            copyCode.on('success', function (event) {
                event.clearSelection();
                event.trigger.textContent = 'Copied';
                window.setTimeout(function () {
                    event.trigger.textContent = 'Copy';
                }, 2000);
            });
            copyCode.on('error', function (event) {
                event.trigger.textContent = 'Press "Ctrl + C" to copy';
                window.setTimeout(function () {
                    event.trigger.textContent = 'Copy';
                }, 2000);
            });
        });
</script>

Based on: http://webdesign.tutsplus.com/tutorials/copy-to-clipboard-made-easy-with-clipboardjs--cms-25086