2024-04-14 12:41:22 +00:00
|
|
|
import { Behavior, registerBehavior } from "./index";
|
2023-10-07 08:24:09 +00:00
|
|
|
|
2024-04-14 12:41:22 +00:00
|
|
|
class DropdownBehavior extends Behavior {
|
2023-10-07 08:24:09 +00:00
|
|
|
constructor(element) {
|
2024-04-14 12:41:22 +00:00
|
|
|
super(element);
|
2023-10-07 08:24:09 +00:00
|
|
|
this.opened = false;
|
|
|
|
this.onOutsideClick = this.onOutsideClick.bind(this);
|
|
|
|
|
|
|
|
const toggle = element.querySelector(".dropdown-toggle");
|
|
|
|
toggle.addEventListener("click", () => {
|
|
|
|
if (this.opened) {
|
|
|
|
this.close();
|
|
|
|
} else {
|
|
|
|
this.open();
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
open() {
|
|
|
|
this.element.classList.add("active");
|
|
|
|
document.addEventListener("click", this.onOutsideClick);
|
|
|
|
}
|
|
|
|
|
|
|
|
close() {
|
|
|
|
this.element.classList.remove("active");
|
|
|
|
document.removeEventListener("click", this.onOutsideClick);
|
|
|
|
}
|
|
|
|
|
|
|
|
onOutsideClick(event) {
|
|
|
|
if (!this.element.contains(event.target)) {
|
|
|
|
this.close();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
registerBehavior("ld-dropdown", DropdownBehavior);
|