Skip to content

Instantly share code, notes, and snippets.

@jinjor
Created February 27, 2019 19:00
Show Gist options
  • Save jinjor/66b10f6269732f67a119da0011ff8558 to your computer and use it in GitHub Desktop.
Save jinjor/66b10f6269732f67a119da0011ff8558 to your computer and use it in GitHub Desktop.
class SelectListElement extends HTMLElement {
constructor() {
super();
this.addEventListener("click", e => {
let target = e.target as Element;
while (target.parentElement !== this) {
target = target.parentElement;
}
if (target instanceof SelectItemElement) {
e.stopPropagation();
let changed = false;
for (let el of this.children) {
if (el === target) {
changed = el.hasAttribute("selected");
el.setAttribute("selected", "");
} else {
el.removeAttribute("selected");
}
}
if (changed) {
this.dispatchEvent(new Event("change", { bubbles: true }));
}
}
});
}
get value(): string {
for (let el of this.children) {
if (el instanceof SelectItemElement && el.hasAttribute("selected")) {
return el.value;
}
}
return null;
}
}
customElements.define("select-list", SelectListElement);
class SelectItemElement extends HTMLElement {
constructor() {
super();
}
get value(): string {
return this.getAttribute("value");
}
}
customElements.define("select-item", SelectItemElement);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment