click-to-copy.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. } catch (err) {
  17. console.error('Fallback: Oops, unable to copy', err);
  18. }
  19. document.body.removeChild(textArea);
  20. }
  21. function copyTextToClipboard(text) {
  22. if (!navigator.clipboard) {
  23. fallbackCopyTextToClipboard(text);
  24. return;
  25. }
  26. navigator.clipboard.writeText(text).then(function() {
  27. console.log('Async: Copying to clipboard was successful!');
  28. }, function(err) {
  29. console.error('Async: Could not copy text: ', err);
  30. });
  31. }
  32. function init() {
  33. $(document)
  34. .off('click.click-to-copy', '.click-to-copy')
  35. .on('click.click-to-copy', '.click-to-copy', function(event) {
  36. copyTextToClipboard($(this).text());
  37. });
  38. }
  39. addMCInitializer('click-to-copy', init);
  40. }).call(window);