Edward Coast
Edward Coast

Reputation: 384

How do I change the button to say "Copied!" after text is copied to clipboard using clipboard.js?

The following HTML page is from a demo for clipboard.js from clipboardjs.com. I like how this works, where it highlights the text.

However, I have a requirement to have it change the button from displaying "Copy" to "Copied!" once the user has clicked on the button and it has successfully completed the copy to clipboard.

   <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>target-input</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
    </head>
    <body>
        <!-- 1. Define some markup -->
        <input id="foo" type="text" value="hello">
        <button class="btn" data-clipboard-action="copy" data-clipboard-target="#foo">Copy</button>

        <!-- 2. Include library -->
        <script src="../dist/clipboard.min.js"></script>

        <!-- 3. Instantiate clipboard -->
        <script>
        var clipboard = new Clipboard('.btn');

        clipboard.on('success', function(e) {
            console.log(e);
        });

        clipboard.on('error', function(e) {
            console.log(e);
        });
        </script>
    </body>
    </html>

Upvotes: 0

Views: 2272

Answers (2)

Jefferson
Jefferson

Reputation: 794

This worked for me:

clipboard.on('success', function(e) {
    e.clearSelection();
    e.trigger.textContent = 'Copied!';
});

Quoting from this tutorial on the part of Working with the Custom Events:

  • First, we clear selection within the area of the copied content using the clearSelection() utility function from Clipboard. Adding this is optional.
  • Then we set the content to “Copied!”

Upvotes: 3

quirimmo
quirimmo

Reputation: 9988

clipboard.on('success', function(e) {
  document.querySelector('data-clipboard-target="#foo"').value = 'Copied!';
});

Upvotes: 0

Related Questions