jquery.copy-to-clipboard.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. /*
  2. * Copyright (c) 2016 Milan Kyncl
  3. * Licensed under the MIT license.
  4. *
  5. * jquery.copy-to-clipboard plugin
  6. * https://github.com/mmkyncl/jquery-copy-to-clipboard
  7. *
  8. */
  9. $.fn.CopyToClipboard = function() {
  10. var textToCopy = false;
  11. if(this.is('select') || this.is('textarea') || this.is('input')){
  12. textToCopy = this.val();
  13. }else {
  14. textToCopy = this.text();
  15. }
  16. CopyToClipboard(textToCopy);
  17. };
  18. function CopyToClipboard( val ){
  19. var hiddenClipboard = $('#_hiddenClipboard_');
  20. if(!hiddenClipboard.length){
  21. $('body').append('<textarea style="position:absolute;top: -9999px;" id="_hiddenClipboard_"></textarea>');
  22. hiddenClipboard = $('#_hiddenClipboard_');
  23. }
  24. hiddenClipboard.html(val);
  25. hiddenClipboard.select();
  26. document.execCommand('copy');
  27. document.getSelection().removeAllRanges();
  28. }
  29. $(function(){
  30. $('[data-clipboard-target]').each(function(){
  31. $(this).click(function() {
  32. $($(this).data('clipboard-target')).CopyToClipboard();
  33. });
  34. });
  35. $('[data-clipboard-text]').each(function(){
  36. $(this).click(function(){
  37. CopyToClipboard($(this).data('clipboard-text'));
  38. });
  39. });
  40. });
  41. $('#randomKey').click(function(){
  42. $(this).CopyToClipboard();
  43. });