forked from mdn/web-components-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
76 lines (61 loc) · 2.15 KB
/
main.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
customElements.define('person-details',
class extends HTMLElement {
constructor() {
super();
const template = document.getElementById('person-template');
const templateContent = template.content;
const shadowRoot = this.attachShadow({mode: 'open'});
const style = document.createElement('style');
style.textContent = `
div { padding: 10px; border: 1px solid gray; width: 200px; margin: 10px; }
h2 { margin: 0 0 10px; }
ul { margin: 0; }
p { margin: 10px 0; }
`;
shadowRoot.appendChild(style);
shadowRoot.appendChild(templateContent.cloneNode(true));
}
}
);
customElements.define('edit-word',
class extends HTMLElement {
constructor() {
super();
const shadowRoot = this.attachShadow({mode: 'open'});
const form = document.createElement('form');
const input = document.createElement('input');
const span = document.createElement('span');
const style = document.createElement('style');
style.textContent = 'span { background-color: #eef; padding: 0 2px }';
shadowRoot.appendChild(style);
shadowRoot.appendChild(form);
shadowRoot.appendChild(span);
span.textContent = this.textContent;
input.value = this.textContent;
form.appendChild(input);
form.style.display = 'none';
span.style.display = 'inline-block';
input.style.width = span.clientWidth + 'px';
this.setAttribute('tabindex', '0');
input.setAttribute('required', 'required');
this.style.display = 'inline-block';
this.addEventListener('click', () => {
span.style.display = 'none';
form.style.display = 'inline-block';
input.focus();
input.setSelectionRange(0, input.value.length)
});
form.addEventListener('submit', e => {
updateDisplay();
e.preventDefault();
});
input.addEventListener('blur', updateDisplay);
function updateDisplay() {
span.style.display = 'inline-block';
form.style.display = 'none';
span.textContent = input.value;
input.style.width = span.clientWidth + 'px';
}
}
}
);