Home > Back-end >  How do I get the ID of the clicked button when using ClipboardJS?
How do I get the ID of the clicked button when using ClipboardJS?

Time:12-03

I do not really do much with JavaScript and this is my first time using ClipboardJS; nevertheless, when I try to get the ID of my button it returns undefined. Is there a way get the ID of a button when using ClipboardJS?

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

clipboard.on('success', function(e) {
  console.info('Text:', e.text);
  console.info('ID:', this.id);
  console.info('Target:', e.target);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.8/clipboard.min.js"></script>

<button id="someID" class="btn" data-clipboard-text="Just because you can doesn't mean you should — clipboard.js">
Copy to clipboard
</button>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

The event being passed to the function is not a standard DOM Event which will contain properties like id or target. Instead, it is a custom event from ClipboardJS.

If you log just the event e you can see the properties that their custom event object contains. There is a trigger property which contains the element and allows you to get the id.

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

clipboard.on('success', function(e) {
  console.info('ClipboardJS Event:', e);
  console.info('Trigger:', e.trigger);
  console.info('Trigger ID:', e.trigger.id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.8/clipboard.min.js"></script>

<button id="someID" class="btn" data-clipboard-text="Just because you can doesn't mean you should — clipboard.js">
Copy to clipboard
</button>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related