|
| 1 | +/** |
| 2 | + * Include code to enable copy-to-clipboard functionality |
| 3 | + * and currently used on index and matrix tables |
| 4 | + * @example in Haml |
| 5 | + * %div.clippable |
| 6 | + * = Text to be copied |
| 7 | + * %button.clippy.hidden{ title: "Copy to clipboard" } |
| 8 | + * %span.glyphicon.glyphicon-copy |
| 9 | + */ |
| 10 | + |
| 11 | +/** |
| 12 | + * Bootstrap copy-to-clipboard functionality |
| 13 | + * @param {string} selector CSS selector of elements that require |
| 14 | + * copy-to-clipboard functionality |
| 15 | + */ |
| 16 | +function initializeClipper(selector) { |
| 17 | + const elements = $(selector); |
| 18 | + |
| 19 | + elements.hover(function() { |
| 20 | + $(this).children(".clippy").toggleClass("hidden"); |
| 21 | + }); |
| 22 | + |
| 23 | + elements |
| 24 | + .children(".clippy") |
| 25 | + .click(function() { |
| 26 | + const clippyButton = $(this); |
| 27 | + const text = $.trim(clippyButton.closest(selector).text()); |
| 28 | + |
| 29 | + copyToClipboard(text); |
| 30 | + flashClipped(clippyButton); |
| 31 | + }); |
| 32 | +} |
| 33 | + |
| 34 | +/** |
| 35 | + * Copy text to clipboard using execCommand |
| 36 | + * @see https://gist.github.com/Chalarangelo/4ff1e8c0ec03d9294628efbae49216db#file-copytoclipboard-js |
| 37 | + * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand |
| 38 | + * @param {string} text text to be copied to clipboard |
| 39 | + */ |
| 40 | +function copyToClipboard(text) { |
| 41 | + const el = document.createElement('textarea'); |
| 42 | + el.value = text; |
| 43 | + el.setAttribute('readonly', ''); |
| 44 | + el.style.position = 'absolute'; |
| 45 | + el.style.left = '-9999px'; |
| 46 | + document.body.appendChild(el); |
| 47 | + |
| 48 | + const selected = |
| 49 | + document.getSelection().rangeCount > 0 |
| 50 | + ? document.getSelection().getRangeAt(0) |
| 51 | + : false; |
| 52 | + el.select(); |
| 53 | + document.execCommand('copy'); |
| 54 | + document.body.removeChild(el); |
| 55 | + if (selected) { |
| 56 | + document.getSelection().removeAllRanges(); |
| 57 | + document.getSelection().addRange(selected); |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +/** |
| 62 | + * Flash a success tick to indicate successful copy-to-clipboard action |
| 63 | + * @param {jQuery Element} clipButton button to copy to clipboard |
| 64 | + */ |
| 65 | +function flashClipped(clippyButton) { |
| 66 | + const icon = clippyButton.children("span"); |
| 67 | + icon.attr("class", "glyphicon glyphicon-ok success"); |
| 68 | + |
| 69 | + setTimeout( |
| 70 | + function() { icon.attr("class", "glyphicon glyphicon-copy"); }, |
| 71 | + 2000 |
| 72 | + ); |
| 73 | +} |
0 commit comments