How to use event delegation when using clipboardjs?

410 views Asked by At

Clipboardjs is awesome, but I wonder how to use event delegation when using it.

Here is my code:

<script src="https://cdn.jsdelivr.net/clipboard.js/1.5.16/clipboard.min.js"></script>
<body>
  <code id="target0">0</code>
  <code id="target1">1</code>
  <code id="target2">2</code>
  <input type="button" value="copy" class="btn0" data-clipboard-action="copy" data-clipboard-target="#target0"/>
  <input type="button" value="copy" class="btn1" data-clipboard-action="copy" data-clipboard-target="#target1"/>
  <input type="button" value="copy" class="btn2" data-clipboard-action="copy" data-clipboard-target="#target2"/>

  <script>
    // new Clipboard('.btn0');
    // new Clipboard('.btn1');
    // new Clipboard('.btn2');

    var btns = document.querySelectorAll('input[type="button"]');
    var clipboard = new Clipboard(btns);
  </script>
</body>

it works well, but it will attach event listeners for three dom elements, so I want to optimize it by using event delegation, I read the guide, it's not mentioned, maybe it is:

For this reason we use event delegation which replaces multiple event listeners with just a single listener

so I come here for help.

Could you please modify my demo using event delegation?

2

There are 2 answers

0
fshaw1 On BEST ANSWER

From the guide, it looks like if you add the same class to all three buttons (i.e., something like "btn"), and then pass that class selector to clipboard it should do the event delegation for you.

<script src="https://cdn.jsdelivr.net/clipboard.js/1.5.16/clipboard.min.js"></script>
<body>
  <code id="target0">0</code>
  <code id="target1">1</code>
  <code id="target2">2</code>
  <input type="button" value="copy" class="btn btn0" data-clipboard-action="copy" data-clipboard-target="#target0"/>
  <input type="button" value="copy" class="btn btn1" data-clipboard-action="copy" data-clipboard-target="#target1"/>
  <input type="button" value="copy" class="btn btn2" data-clipboard-action="copy" data-clipboard-target="#target2"/>

  <script>
    var clipboard = new Clipboard('.btn');
  </script>
</body>
1
Zeno Rocha On

Clipboard.js creator here :) We already do event delegation for you. All you need is to pass a string selector to the constructor instead of an element.

With event delegation

var clipboard = new Clipboard('.btn');

Without event delegation

var btns = document.querySelectorAll('input[type="button"]'); var clipboard = new Clipboard(btns);