Quick tricks - implement a copy button
Sometimes you want to make it easy for people to copy something to the clipboard. Using the navigator.clipboard
API, this is pretty straightforward.
Given this HTML:
<button class="copybutton"
data-payload="Your Data"
data-label="Copied!"
data-time="1000">Copy</button>
You can write an Event Handler using Event Delegation to read the info and use it.
document.addEventListener('click', (e) => {
if (e.target.classList.contains('copybutton')) {
let text = e.target.innerText;
e.target.dataset.original = text;
let payload = e.target.dataset.payload || text;
let label = e.target.dataset.label || 'Copied!';
let time = e.target.dataset.time || 1000;
navigator.clipboard.writeText(payload).then(() => {
console.log('Copied: ' + payload);
e.target.textContent = label;
setTimeout(() => {
e.target.innerText = e.target.dataset.original;
}, time);
}, () => {
console.error('Failed to copy ' + copy);
});
}
});
You can use any amount of buttons you want and you can alter the settings:
data-payload
is the text to copy - if you don’t provide one, it copies the text of the buttondata-label
is the message displayed when the data was copied to the clipboard (preset is “Copied!”)data-time
is the amount of milliseconds to show the label message (preset is 1000)
Check out the demopage for more examples.
These tricks are part of the Dev Digest Newsletter.