The original problem was how to implement a copy button across browsers using clipboardData.
Internet Explorer supported window.clipboardData.setData('text', 'content').
In IE, clipboardData was a property of window.
Other browsers expose clipboard data on the corresponding event object. That design helps prevent unauthorized access. For cross-browser support, my original conclusion was that we could not implement click to copy with .clipboardData
💡 Update: Modern browsers also provide a Clipboard API for writing data directly to the clipboard.
Here is the approach I used:
Create a hidden input field.
When the user clicks the button, put the text to copy into that field.
Select the contents with input.select().
This selection method works on an input or a textarea.
// document.execCommand("copy") executes the browser's copy command.
function copyText() {
var text = document.getElementById("text").innerText; // The text can also be passed as an argument.
var input = document.getElementById("input"); // Find the hidden input.
input.value = text; // Set the field's value.
input.select(); // Select the text.
document.execCommand("copy"); // Run the browser's copy command.
alert("Copied");
}