Click button to copy text to clipboard

This is something that I use a lot and thought you might find it useful. In the video I explain how it’s used. And further down this page you will find the Javascript code to put on the page to make it work.

Naming for the data attributes

Data Attribute Name Element to put it on
data-copy-text Text element that you want to copy to clipboard.
data-copy-button Button or image you want to have as the clickable item to run the copy script.
data-copy-message A blank text element that will display the confirmation that it was copied.

Get the code

Copy the javascript below and paste it into a code element in the javascript box. Do not forget to clear out the HTML box, and to approve running the code. The Data Attributes are as follows:

document.querySelector('[data-copy-button]').addEventListener('click', function() {
    const text = document.querySelector('[data-copy-text]').innerText;
    const message = document.querySelector('[data-copy-message]');

    navigator.clipboard.writeText(text).then(() => {
        message.innerText = "Copied to clipboard!";
    }).catch(() => {
        message.innerText = "Failed to copy";
    });

    setTimeout(() => {
        message.innerText = "";
    }, 2000); // Message disappears after 2 seconds
});