Refactor language switcher using class

This commit is contained in:
Kitaiti Makoto 2020-12-29 19:40:22 +09:00
parent 77bb510e93
commit c4ebde8951

View file

@ -3,20 +3,41 @@ document.getElementById('menu').addEventListener('click', evt =>
) )
document.addEventListener('DOMContentLoaded', () => { document.addEventListener('DOMContentLoaded', () => {
for (const switcher of document.getElementsByClassName('language-switcher')) { class LanguageSwitcher {
const control = switcher.querySelector('[aria-haspopup]'); constructor(element) {
control.addEventListener('click', event => { this.element = element;
const popupId = control.getAttribute('aria-controls'); this.control = this.element.querySelector('[aria-haspopup]');
if (! popupId) return; const popupId = this.control.getAttribute('aria-controls');
const popup = document.getElementById(popupId); this.popup = document.getElementById(popupId);
if (! popup) return; this.control.addEventListener('click', _ => {this.toggle();});
if (control.getAttribute('aria-expanded') === 'true') {
control.setAttribute('aria-expanded', 'false');
popup.setAttribute('aria-hidden', 'true');
} else {
control.setAttribute('aria-expanded', 'true');
popup.setAttribute('aria-hidden', 'false');
} }
});
get expanded() {
return this.control.getAttribute('aria-expanded') === 'true';
}
toggle() {
if (this.expanded) {
this.collapse();
} else {
this.expand();
}
}
expand() {
if (this.expanded) return;
this.control.setAttribute('aria-expanded', 'true');
this.popup.setAttribute('aria-hidden', 'false');
}
collapse() {
if (! this.expanded) return;
this.control.setAttribute('aria-expanded', 'false');
this.popup.setAttribute('aria-hidden', 'true');
}
}
for (const switcher of document.getElementsByClassName('language-switcher')) {
new LanguageSwitcher(switcher);
} }
}); });