1

I've been working on a project in which I need to copy a URL to the user's clipboard upon them clicking on a link. I'm aware that there's much documentation about this online, especially with Clipboard JS and this great question, but all of these references seem to show examples of obtaining a value from a button or text field, which is not my use case.

In my case, I have a JQuery variable designed as such;

var destination = $(this).attr('href');

My goal is to take destination and set it as the text string that will be copied to the clipboard (I have the click event already set up and can confirm it is functioning via alerts).

This is my most recent attempt;

var destination = $(this).attr('href');
var $temp = $("<input>");
$("body").append($temp);
$temp.val(destination).select();
document.execCommand("copy");
$temp.remove();

This, however, has proven largely unsuccessful as nothing is ever copied to the clipboard.

ZbadhabitZ
  • 2,753
  • 1
  • 25
  • 45

1 Answers1

0

I really recommend this package: https://github.com/zenorocha/clipboard.js.git

I've used it before and it works like a charm!

  • Thanks for the suggestion! I have indeed try that package, but have had no success. If anyone is able to provide some guidance on how it could be instantiated given the sample variable above, I'd love to work with it! – ZbadhabitZ Mar 02 '18 at 03:16
  • It turns out this issue was being caused by my trying to initiate the copy from inside a modal that was preventing the copy from working. When testing outside of the modal, `ClipboardJS` functioned great. I'm marking this answer as correct. It's not the only solution, but it sure was easy. – ZbadhabitZ Mar 02 '18 at 22:01