Copy to the clipboard in JS

   // Code from http://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript
    function copyTextToClipboard(text) {
        var textArea              = document.createElement("textarea");
        textArea.style.position   = 'fixed';
        textArea.style.top        = 0;
        textArea.style.left       = 0;
        textArea.style.width      = '2em';
        textArea.style.height     = '2em';
        textArea.style.padding    = 0;
        textArea.style.border     = 'none';
        textArea.style.outline    = 'none';
        textArea.style.boxShadow  = 'none';
        textArea.style.background = 'transparent';
        textArea.value            = text;

        document.body.appendChild(textArea);
        textArea.select();

        try {
          var successful = document.execCommand('copy');
          var msg = successful ? 'successful' : 'unsuccessful';
          console.log('Copying text command was ' + msg);
        } catch (err) {
          alert('La copie dans le presse-papier ne fonctionne pas sur ce navigateur.');
        }

        document.body.removeChild(textArea);
        return successful;
    }

Then, there is two ways:

onClick and input[type=text]

Your input:

<input type="text" value="foobar" onclick="copyThis('<?php echo $str; ?>', this); select()" />

Note that select() alone select all the content of the input text but is optional. Then:

function copyThis(text, item) {
        var success = copyTextToClipboard(text);
        if(success) {
            item.classList.add('copied');
            window.setTimeout(function(){
                item.classList.remove('copied');
            }, 750);
        }
    }

addEventListener

var element = document.getElementById('clipboard');
element.classList.remove('hidden'); // element is only showed when JS is available
element.addEventListener('click', function(e){
   e.preventDefault(); // Cancel the native event
   e.stopPropagation();// Don't bubble/capture the event
    success = copyTextToClipboard('<?php echo $str; ?>');
        if(success) {
            element.classList.add('copied');
            window.setTimeout(function(){
                element.classList.remove('copied');
            }, 750);
        }
 }, false);

The first one seems more versatile when using PHP, since you don't have to write the string inside a function at the bottom of a page/on another document. Of course we could use a data attribute ton store the string, and get used by the Event Listener.