-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTargetElement.js
More file actions
70 lines (59 loc) · 1.83 KB
/
TargetElement.js
File metadata and controls
70 lines (59 loc) · 1.83 KB
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
const ttsTargetTemplateString = `
<style>
#text-content { display: none; }
</style>
<div id="text-content">
<slot name="text-content"></slot>
</div>
<span>
<slot></slot>
</span>
`;
class TTSTargetElement extends HTMLElement {
constructor() {
super();
this.template = document.createElement('template');
this.template.innerHTML = ttsTargetTemplateString;
this.attachShadow({mode: 'open'});
this.shadowRoot.append(
this.template.content.cloneNode(true)
);
// Bound methods
this.handleClick = this.handleClick.bind(this);
}
connectedCallback(){
if(!this.isConnected){
return;
}
this.span = this.shadowRoot.querySelector('span');
this.addEventListener('click', this.handleClick);
this.textSlot = this.shadowRoot.querySelector('slot[name="text-content"]');
}
disconnectedCallback(){
this.removeEventListener('click', this.handleClick);
}
handleClick(){
const target = document.querySelector(
this.getAttribute('target')
);
if(!target){
return;
}
if(!this.classList.contains('active')){
// Clear any existing targets
Array.from(document.querySelectorAll('tts-target.active')).forEach(el => {
el.classList.remove('active');
});
const slottedElements = this.textSlot.assignedNodes().map(el => {
return el.cloneNode(true);
});
target.innerHTML = "";
target.append(...slottedElements);
} else {
target.innerHTML = "";
}
this.span.classList.toggle('active');
this.classList.toggle('active');
}
};
window.customElements.define('tts-target', TTSTargetElement);