Search code examples
javascriptphphtmljscriptclipboard.js

Using clipboard.js with generated PHP input


I'm not experienced using JScript and using it only, when there is no other option. But I want the user of my site give the option to copy a specific generated PHP-Code into his clipboard.

I have the following Code

<?php 
    echo'<button class="btn" data-clipboard-text="'. htmlspecialchars("<pre><code>", ENT_HTML5) . $newText . htmlspecialchars("</code></pre>", ENT_HTML5) .'">Copy to Clipboard</button>';
?>
<script src="./clipboard.js"></script>
<script>
    var btn = document.getElementById('btn');
    var clipboard = new Clipboard(btn);
    clipboard.on('success', function(e) {
        console.log(e);
    });
    clipboard.on('error', function(e) {
        console.log(e);
    });
</script>

But I'm gettting this error message in Console:

TypeError: First argument must be a String, HTMLElement, HTMLCollection, or NodeList

throw new TypeError('First argument must be a String, HTMLElement, HTMLCollectio...

On line 152 of clipboard.js

What am I doing wrong?


Solution

  • You don't have a button with id set to btn, so getElementById will return null.

    You are passing null to Clipboard.