Copy to Clipboard

I was working on a custom LinkedIn module for Joomla which required a site administrator to copy a long Authorization Code into a field within the module configuration page. I wanted to provide a native Copy to Clipboard function for modern browsers that support that feature.

I first echo’ed the output into a <p> tag and used the following Javascript to successfully execute the Copy to Clipboard command.

document.addEventListener('DOMContentLoaded', function() {
var copybtn = document.getElementById('copybtn');
var authcode = document.getElementById('authcode');
copybtn.addEventListener('click', function() {
// select the authorization code text
var range = document.createRange();
range.selectNode(authcode);
window.getSelection().addRange(range);
try{
// with text selected, execute the copy command
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
if (msg == 'successful') copybtn.value = 'Copied!';
console.log('Copy authorization code command was ' + msg);
} catch(err) {
console.log('Oops, unable to copy');
}
// remove the selection
window.getSelection().removeAllRanges();
});
});

But because hyphens are sometimes used in the Authorization Code, the output would wrap and correcting the wrap using CSS would cause horizontal scrollbars and require more styling. So I decided to output the Authorization Code as the value of an <input> text field. However, the same Javascript caused additional whitespace to be prepended to the Authorization Code when pasting it into the field within the module configuration page. To fix this, I had to modify the Javascript as follows:

document.addEventListener('DOMContentLoaded', function() {
var copybtn = document.getElementById('copybtn');
var authcode = document.getElementById('authcode');
copybtn.addEventListener('click', function() {
// select the authorization code value
authcode.setSelectionRange(0, authcode.value.length);
try{
// with text selected, execute the copy command
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
if (msg == 'successful') copybtn.value = 'Copied!';
console.log('Copy authorization code command was ' + msg);
} catch(err) {
console.log('Oops, unable to copy');
}
// remove the selection
window.getSelection().removeAllRanges();
});
});