Briefly

I would like to add a button to the site so that you can quickly copy pieces of code. The search shows that the easiest task to accomplish with Clipboard.js . But I cannot connect this script, and on Codepen.io and in the built-in Stack Overflow snippets the same code works as it should.



Minimum code example

Additionally, I connected only Rainbow for highlighting so that the desired behavior was visually understandable.

new Clipboard('.SashaButton'); 
  body { background: sienna; color: pink; margin: 0; } code { font-size: 19px; } .SashaButton { position: absolute; right: 0.5rem; top: 0.5rem; } 
 <!doctype html> <html lang="en"> <head> <meta charset=utf-8> <meta name=description content=""> <meta name=viewport content="width=device-width, initial-scale=1"> <title></title> <script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/1.4.0/clipboard.min.js"></script> <script src="http://Kristinita.ru/bower-components/rainbow/dist/rainbow.min.js"></script> <link rel="stylesheet" type="text/css" href="http://Kristinita.ru/bower-components/rainbow/themes/css/espresso-libre.css"> </head> <body> <p>Test code:</p> <pre class="SashaClipboard1"><code>Саша прекрасна!</code>&nbsp;<button class="SashaButton" data-clipboard-target=".SashaClipboard1"><img src="https://clipboardjs.com/assets/images/clippy.svg" alt="Copy to clipboard" width="13"></button></pre> <p>Example</p> <p>Another example code:</p> <pre class="SashaClipboard2"><code data-language="json"> &quot;Sasha&quot;: &quot;never&quot;, &quot;forgive&quot;: &quot;me&quot; </code><button class="SashaButton" data-clipboard-target=".SashaClipboard2"><img src="https://clipboardjs.com/assets/images/clippy.svg" alt="Copy to clipboard" width="13"></button></pre> </body> </html> 



Desired behavior

http://codepen.io/Kristinita/pen/bwzXqR

Desired behavior



Actual behavior

The code does not work both on the site - http://kristinita.ru/Sublime-Text/Test - and on the local server. Tested on the latest versions of Firefox, Chrome and Opera.

Why this happens, did not understand, additional dependencies , according to the official site, do not need to be installed.



Firebug

Firebug shows an error:

 TypeError: a is null 

Firebug error

To understand further does not work.



Questions

  • How to connect Clipboard.js to the site in order to get the desired behavior?
  • If you explain why the code works here and on Codepen.io, but does not work on the site, it will be nice.

    1 answer 1

    I could not reproduce your problem through file:// and on the local host.
    Chrome 53, FF 49 .

    1. <script src='/path/to/clipboard.js'></script> .
      But you need to initialize in the style:
      document.addEventListener('DOMContentLoaded', _ => new Clipboard('.SashaButton')); .
    2. Due to the impossibility of reproducing, it is not possible to say what is wrong.