Clipboard.js: Only copying on the second time it is clicked

Created on 8 Dec 2016  路  8Comments  路  Source: zenorocha/clipboard.js

My code

`

                  <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');
                    }
                 })

`

Actual behaviour

It is only copying to the clipboard on the second click. I have tried using both a cdn and webpack script-loader.

Browsers affected

Chrome 54

Any help would be appreciated, thank you.

Most helpful comment

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.

All 8 comments

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
png
Log:
ValReqd: https://www.google.com

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..

Was this page helpful?
0 / 5 - 0 ratings

Related issues

eltonjude picture eltonjude  路  3Comments

bravo14 picture bravo14  路  3Comments

168tickets picture 168tickets  路  6Comments

dweepcan picture dweepcan  路  3Comments

XZZsr picture XZZsr  路  5Comments