0

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>
Edward Coast
  • 374
  • 4
  • 17

2 Answers2

3

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!”
Jefferson
  • 794
  • 10
  • 24
  • Thanks. I tried it with and without the e.clearSelection();. We prefer it without the e.clearSelection(); since it functions like the demo where it highlights the text input. – Edward Coast Sep 19 '17 at 23:27
0
clipboard.on('success', function(e) {
  document.querySelector('data-clipboard-target="#foo"').value = 'Copied!';
});
quirimmo
  • 9,800
  • 3
  • 30
  • 45