Guest User

Untitled

a guest
Nov 23rd, 2017
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.30 KB | None | 0 0
  1. /**
  2. * @param {String} HTML representing a single element
  3. * @return {Element}
  4. */
  5. function htmlToElement(html) {
  6. var template = document.createElement('template');
  7. template.innerHTML = html;
  8. return template.content.firstChild;
  9. }
  10.  
  11.  
  12. /**
  13. * @param {String} HTML representing any number of sibling elements
  14. * @return {NodeList}
  15. */
  16. function htmlToElements(html) {
  17. var template = document.createElement('template');
  18. template.innerHTML = html;
  19. return template.content.childNodes;
  20. }
  21.  
  22. function copyTextToClipboard(text) {
  23. if (!text) {
  24. console.warn("text to be copied is empty and the clipboard will not be updated");
  25. }
  26.  
  27. var textArea = document.createElement("textarea");
  28.  
  29. //
  30. // *** This styling is an extra step which is likely not required. ***
  31. //
  32. // Why is it here? To ensure:
  33. // 1. the element is able to have focus and selection.
  34. // 2. if element was to flash render it has minimal visual impact.
  35. // 3. less flakyness with selection and copying which **might** occur if
  36. // the textarea element is not visible.
  37. //
  38. // The likelihood is the element won't even render, not even a flash,
  39. // so some of these are just precautions. However in IE the element
  40. // is visible whilst the popup box asking the user for permission for
  41. // the web page to copy to the clipboard.
  42. //
  43.  
  44. // Place in top-left corner of screen regardless of scroll position.
  45. textArea.style.position = 'fixed';
  46. textArea.style.top = 0;
  47. textArea.style.left = 0;
  48.  
  49. // Ensure it has a small width and height. Setting to 1px / 1em
  50. // doesn't work as this gives a negative w/h on some browsers.
  51. textArea.style.width = '2em';
  52. textArea.style.height = '2em';
  53.  
  54. // We don't need padding, reducing the size if it does flash render.
  55. textArea.style.padding = 0;
  56.  
  57. // Clean up any borders.
  58. textArea.style.border = 'none';
  59. textArea.style.outline = 'none';
  60. textArea.style.boxShadow = 'none';
  61.  
  62. // Avoid flash of white box if rendered for any reason.
  63. textArea.style.background = 'transparent';
  64.  
  65.  
  66. textArea.value = text;
  67.  
  68. document.body.appendChild(textArea);
  69.  
  70. textArea.select();
  71.  
  72. try {
  73. var successful = document.execCommand('copy');
  74. var msg = successful ? 'successful' : 'unsuccessful';
  75. } catch (err) {
  76. console.error('Oops, unable to copy');
  77. }
  78.  
  79. document.body.removeChild(textArea);
  80. }
Add Comment
Please, Sign In to add comment