click-to-copy.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. (function() {
  2. function fallbackCopyTextToClipboard(text) {
  3. var textArea = document.createElement("textarea");
  4. textArea.value = text;
  5. // Avoid scrolling to bottom
  6. textArea.style.top = "0";
  7. textArea.style.left = "0";
  8. textArea.style.position = "fixed";
  9. document.body.appendChild(textArea);
  10. textArea.focus();
  11. textArea.select();
  12. try {
  13. var successful = document.execCommand('copy');
  14. var msg = successful ? 'successful' : 'unsuccessful';
  15. console.log('Fallback: Copying text command was ' + msg);
  16. toastr.success('Copied!');
  17. } catch (err) {
  18. console.error('Fallback: Oops, unable to copy', err);
  19. }
  20. document.body.removeChild(textArea);
  21. }
  22. function copyTextToClipboard(text) {
  23. if (!navigator.clipboard) {
  24. fallbackCopyTextToClipboard(text);
  25. return;
  26. }
  27. navigator.clipboard.writeText(text).then(function() {
  28. console.log('Async: Copying to clipboard was successful!');
  29. toastr.success('Copied!');
  30. }, function(err) {
  31. console.error('Async: Could not copy text: ', err);
  32. });
  33. }
  34. function init() {
  35. $(document)
  36. .off('click.click-to-copy', '.click-to-copy')
  37. .on('click.click-to-copy', '.click-to-copy', function(event) {
  38. copyTextToClipboard($(this).text());
  39. });
  40. window.copyTextToClipboard = copyTextToClipboard;
  41. }
  42. addMCInitializer('click-to-copy', init);
  43. }).call(window);