forked from sudodoki/copy-button
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
39 lines (35 loc) · 1.13 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
'use strict';
require('document-register-element');
var copy = require('copy-to-clipboard');
var CopyButtonPrototype = Object.create(HTMLButtonElement.prototype);
function handleCopyClick(event) {
if (event.defaultPrevented) return;
if (this.hasAttribute('target-text')) {
return copy(this.getAttribute('target-text'));
}
if (this.hasAttribute('target-element')) {
var toCopyEl = document.querySelector(this.getAttribute('target-element'));
return copy(toCopyEl.value || toCopyEl.textContent || '');
}
}
CopyButtonPrototype.createdCallback = function() {
this.wrappedInButton = false;
};
CopyButtonPrototype.attachedCallback = function() {
if (this.wrappedInButton) return;
var button = document.createElement('button');
if (this.childNodes.length) {
var node;
while (node = this.firstChild) {
button.appendChild(node);
}
} else {
button.textContent = 'Click to copy to clipboard';
}
this.appendChild(button);
this.addEventListener('click', handleCopyClick);
this.wrappedInButton = true;
};
module.exports = document.registerElement('copy-button', {
prototype: CopyButtonPrototype,
});