`
<button id="copy-to-clipboard"
class="copy-to-clipboard"
data-clipboard-text="https://etc">Copy Invitation Link
</button>
document.addEventListener('click', function(e) {
if (e.target && e.target.classList.contains('copy-to-clipboard')) {
new Clipboard('.copy-to-clipboard');
}
})
`
It is only copying to the clipboard on the second click. I have tried using both a cdn and webpack script-loader.
Chrome 54
Any help would be appreciated, thank you.
Just to note that i am not using a text or input element in addition to the above code. I wonder if this could be the cause?
Clipboard.js already comes with a built-in click event listener, you only need this part:
new Clipboard('.copy-to-clipboard');
Thanks @zenorocha - if you have a moment, could you explain what is actually happening then that causes it so not work on first click when i have added an additional event listener? Thank you
When you write new Clipboard('.something') we already do a document.addEventListener('click') behind the scenes, so you don't need to do another one.
Thanks @zenorocha, if i am not testing your patience too much, what is the underlying problem that is caused by the duplicate event listeners that stop it from working? I really appreciate your quick answer to my original question btw!
@matt-paul
Actually it's a logic error.
document.addEventListener('click', function(e) {
if (e.target && e.target.classList.contains('copy-to-clipboard')) {
Whenever you click on an .copy-to-clipboard element for the first time,
new Clipboard('.copy-to-clipboard');
only then a new Clipboard instance gets created and that clicked .copy-to-clipboard element will be its trigger. The next time you click on that specific trigger, it will do the copying thing.
This makes sense because whenever you click on an .copy-to-clipboard element for the first time, it hasn't become a trigger yet.
Thanks @fahmilatib
@zenorocha

Log:
ValReqd: https://www.google.com
Document
clipb value:
t {listener: Object}
If i run this code individually, it will run in second click, but if i merge this code with my project source, it doesn't work.. would be great if you'd help..
Most helpful comment
When you write
new Clipboard('.something')we already do adocument.addEventListener('click')behind the scenes, so you don't need to do another one.