I spent a good 20 min searching online for this, but couldn\'t find it. What I want is to to be able to copy a text string on click without a button. The text strin
Along with copying the text , you also have to make sure that any previously selected component remains selected after copying to clipboard.
const copyToClipboard = str => { const el = document.createElement('textarea'); // Create a element el.value = str; // Set its value to the string that you want copied el.setAttribute('readonly', ''); // Make it readonly to be tamper-proof el.style.position = 'absolute'; el.style.left = '-9999px'; // Move outside the screen to make it invisible document.body.appendChild(el); // Append the element to the HTML document const selected = document.getSelection().rangeCount > 0 // Check if there is any content selected previously ? document.getSelection().getRangeAt(0) // Store selection if found : false; // Mark as false to know no selection existed before el.select(); // Select the content document.execCommand('copy'); // Copy - only works as a result of a user action (e.g. click events) document.body.removeChild(el); // Remove the element if (selected) { // If a selection existed before copying document.getSelection().removeAllRanges(); // Unselect everything on the HTML document document.getSelection().addRange(selected); // Restore the original selection } };
ps adding the source