WeAreDevelopers logo

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:

Check out the demopage for more examples.

Show all Quick Tricks.

These tricks are part of the Dev Digest Newsletter.

Not signed up for WeAreDevelopers Dev Digest yet?