zenorocha / clipboard.js

:scissors: Modern copy to clipboard. No Flash. Just 3kb gzipped :clipboard:
https://clipboardjs.com
MIT License
33.98k stars 3.98k forks source link

if 2 #copy elements then some bugs #861

Closed Bammede closed 1 year ago

Bammede commented 1 year ago

Expected Behaviour

When placing two elements with id #copy each, both elements copy the content as should be, but there are some bugs:

  1. By pressing the second element on the page, the 1st element shows btn.textContent instead the 2nd one. In other words, I press the 2nd button, content has been copied, btn.textContent shows text "copied" in the 1st button instead on the 2nd one.

To Reproduce

Place 2 buttons on the page with copy feature and press the 2nd one.

Browsers Affected

all major browser (Safari, Firefox, Chrome)

Operational System

Windows

larsbo commented 1 year ago

Don't use the same id for multiple elements in HTML.

Bammede commented 1 year ago

Don't use the same id for multiple elements in HTML.

however, script looks for the particular ID, how to use 2 IDs with settings e.g. #copy1 #copy2 ?

   var clipboard = new ClipboardJS('#copy1');
   clipboard.on('success', function (e) {
      const btn = document.getElementById('copy1');
         btn.textContent = 'copied';
   });
larsbo commented 1 year ago

Use another selector than an id. From the docs:

Now, you need to instantiate it by passing a DOM selector, HTML element, or list of HTML elements.

It's possible to select multiple ids:

var clipboard = new ClipboardJS('#btn1,#btn2');

But I would always try to use a class because you can easily add new buttons without changing the js code:

   var clipboard = new ClipboardJS('.copy-button-class');

   clipboard.on('success', function (e) {
        const btn = e.trigger;
         btn.textContent = 'copied';
   });
Bammede commented 1 year ago

it works thanks