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

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.


1 Answers

Imaginaerum On

You can use clipboardjs instead

Download it:

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>

In your page footer add:

        /* Prism copy to clipbaord for all pre with copytoclipboard class */
        $('pre.copytoclipboard').each(function () {
            $this = $(this);
            $button = $('<button>Copy</button>');
            $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.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);

Based on: