Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I get the ID of the clicked button when using ClipboardJS?

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>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading