Using Clipboard.js to change button text by a class

292 views Asked by At

I found this change button text after click w/ clipboard.js

but it causes an error: $ is not a function, see screenshot below

https://www.awesomescreenshot.com/image/8535357?key=55d48e1db3b3e996966454c551958fac

How can I change the button text with Clipboard.js after someoen have clicked it by a class instead of an ID?

For example, the button text will be changed to 'copied' and after some time it will automatically change back to the original text.

Below is my code:

<button
  class="copyElement"
  data-clipboard-text="123"
>
  <span>Take Me There</span>
</button>

<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.8/clipboard.min.js"></script>

<script>new ClipboardJS('.copyElement');</script>

1

There are 1 answers

0
User863 On BEST ANSWER

Using success event without jQuery

https://clipboardjs.com/#events

var clipboard = new ClipboardJS('.copyElement')

clipboard.on('success', function(e) {
    let oldtext = e.trigger.textContent
    e.trigger.textContent = 'Copied!'
    setTimeout(() => e.trigger.textContent = oldtext, 2000)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.8/clipboard.min.js"></script>

<button class="copyElement" data-clipboard-text="123">
  <span>Take Me There 1</span>
</button>

<button class="copyElement" data-clipboard-text="456">
  <span>Take Me There 2</span>
</button>