HTML5 - Copy To Clipboard

Below is a code example that you can add to your site to have a code section with a button, that when clicked, will copy the code to the user's clipboard. I have done the same thing below, but with a hyperlink instead of a button.


Copy code to clipboard

<pre id="code-to-copy">  
// This is some code
// Another line
</pre>

<p><button id="js-emailcopybtn">Copy to clipboard</button></p>

<script>
var copyCodeBtn = document.querySelector('#js-emailcopybtn');

copyCodeBtn.addEventListener('click', function(event)  
{
    // Select the email link anchor text  
    var emailLink = document.querySelector('#code-to-copy');
    var range = document.createRange();
    range.selectNode(emailLink);
    window.getSelection().addRange(range);

    try
    {
        // Now that we've selected the anchor text, execute the copy command
        var successful = document.execCommand('copy');
        var msg = successful ? 'successful' : 'unsuccessful';
        console.log('Copy email command was ' + msg);
    } 
    catch (err)
    {
        console.log('Oops, unable to copy');
    }

    // Remove the selections - NOTE: Should use
    // removeRange(range) when it is supported
    window.getSelection().removeAllRanges();
});

</script>

Author

Programster

Stuart is a software developer with a passion for Linux and open source projects.

comments powered by Disqus
We are a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for us to earn fees by linking to Amazon.com and affiliated sites. More info.