/
target-toggler.js
56 lines (41 loc) · 1.45 KB
/
target-toggler.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
class TargetToggler extends HTMLElement {
connectedCallback() {
this.toggle = this.querySelector("button");
if (!this.toggle) {
throw new Error(`${this.localName} must contain a <button> element.`);
}
if (!this.visible) this.target.setAttribute("hidden", "");
this.controller = new AbortController();
const { signal } = this.controller;
this.toggle.setAttribute("aria-expanded", this.visible);
this.toggle.setAttribute("aria-controls", this.targetId);
this.toggle.addEventListener("click", () => this.handleClick(), { signal });
}
disconnectedCallback() {
this.controller.abort();
}
handleClick() {
let expanded = this.toggle.getAttribute("aria-expanded") === "true" || false;
this.toggle.setAttribute("aria-expanded", !expanded);
this.target.toggleAttribute("hidden", expanded);
}
get target() {
const el = document.getElementById(this.targetId);
if (!el) {
throw new Error(`${this.localName} cannot find element with id "${this.targetId}".`);
}
return el;
}
get targetId() {
const attr = this.getAttribute("target-id");
if (!attr) {
throw new Error(`${this.localName} requires a "target-id" attribute set to an element id`);
}
return attr;
}
get visible() {
const attr = "target-visible";
return (this.hasAttribute(attr) && this.getAttribute(attr) !== "false") || false;
}
}
window.customElements.define("target-toggler", TargetToggler);