anchorjs
anchorjs copied to clipboard
Is there a way to add onclick handler?
Hi,
My use case is to copy the HREF of a.anchorjs-link into the user's clipboard, using document.execCommand("href"), so that user can, for example, email the url.
So I need to have an onclick hander for a.anchorjs-link. Is there any way to achieve this?
I expect something like the code below to work:
jQuery(document).on('click', '.anchorjs-link', function(e) { alert("Click"); });
Any pointers would be helpful.
@manishkatyan, I tested your code and it's working fine for me. Here's what I did:
- Browse to the bootstrap docs site (since they use both AnchorJS and jQuery).
- Open your browser's developer tools, paste your code snippet into the console, and hit enter.
- Hover over a page heading, click the anchor-js link, and confirm that you see your alert.
To use an onclick handler like this on your own site, I think you just need to make sure to run it after you have run the code for adding AnchorJS to the page. 👍
thanks @bryanbraun!
I added the following code in anchor.js at line 150 to add "click to copy" functionality to anchors. With this, I can click on an anchor to copy the url that I can easily email or share on social network.
anchor.onclick = (function(){ var copyURL = this.href; document.addEventListener('copy', function(e) { e.clipboardData.setData('text/plain', copyURL); e.preventDefault(); }, true); document.execCommand("copy");
});
Ohh, interesting. Are you asking if we can add this feature to the AnchorJS library itself?
We've discussed adding a copy-to-clipboard feature to AnchorJS in the past but we decided not to do it, because of UI complexity and browser support issues. Browser support is improving but I'd still prefer not to add it to AnchorJS at the moment.
I do think we could do a better job of providing some documentation or example code for people who want to add a feature like this after running AnchorJS. If you think that would be an improvement, then maybe this issue can focus on improving the docs.
Closing this issue, as it looks like no additional work is needed. 👍