I believe the execCommand
way of doing this is now deprecated
Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible
The new recommended way would be to use the Clipboard API:
navigator.clipboard.writeText("Write something to the clipboard")
.then(() => {
// Copy worked
});
Here is a snippet, but it might get blocked by browsers since the Stackoverflow code snippet runner uses iframes. The code works when not embedded in an iframe.
function copyById(containerId) {
const text = document.getElementById(containerId).innerHTML;
console.log('Copying text to clipboard: ', text);
navigator.clipboard.writeText(text)
.then(() => {
console.log('Copy worked');
})
.catch(e => console.error('The copy failed: ', e));
}
// add onClick event handler to your button with additional function() to not invoke copyById immediately:
document.getElementById('copy-button').onclick = function() {
copyById('to-copy');
}
<p id="to-copy">Text to copy 2!</p>
<button id="copy-button">Copy to clipboard</button>
<br><br>
<input placeholder="Paste here, to try!">