HTML:
<button type='button' id='btn'>Copy</button>
Js
document.querySelect('#btn').addEventListener('click', function() { copyToClipboard('copy this text'); });
JS / Function:
function copyToClipboard(text) { var selected = false; var el = document.createElement('textarea'); el.value = text; el.setAttribute('readonly', ''); el.style.position = 'absolute'; el.style.left = '-9999px'; document.body.appendChild(el); if (document.getSelection().rangeCount > 0) { selected = document.getSelection().getRangeAt(0) } el.select(); document.execCommand('copy'); document.body.removeChild(el); if (selected) { document.getSelection().removeAllRanges(); document.getSelection().addRange(selected); } };
Ricardo canelas
source share