mirror of
https://github.com/openfoodfoundation/openfoodnetwork
synced 2026-01-24 20:36:49 +00:00
Add on_click_outside behavior on dropdown_controller
"It's a Surprise Tool That Will Help Us Later"
This commit is contained in:
@@ -5,6 +5,11 @@ export default class extends Controller {
|
||||
|
||||
connect() {
|
||||
this.#hide();
|
||||
document.addEventListener("click", this.#onBodyClick.bind(this));
|
||||
}
|
||||
|
||||
disconnect() {
|
||||
document.removeEventListener("click", this.#onBodyClick);
|
||||
}
|
||||
|
||||
toggle() {
|
||||
@@ -15,6 +20,12 @@ export default class extends Controller {
|
||||
}
|
||||
}
|
||||
|
||||
#onBodyClick(event) {
|
||||
if (!this.element.contains(event.target)) {
|
||||
this.#hide();
|
||||
}
|
||||
}
|
||||
|
||||
#show() {
|
||||
this.menuTarget.classList.remove("hidden");
|
||||
this.arrowTarget.dataset.collapsedClass.split(" ").forEach((className) => {
|
||||
|
||||
@@ -44,5 +44,16 @@ describe("Dropdown controller", () => {
|
||||
expect(arrow.classList.contains("expandedCLass2")).toBe(true);
|
||||
expect(arrow.classList.contains("collapsedClass")).toBe(false);
|
||||
});
|
||||
|
||||
it ("hide menu when click outside", () => {
|
||||
const dropdown = document.getElementById("dropdown");
|
||||
const menu = document.getElementById("menu");
|
||||
dropdown.click();
|
||||
expect(menu.classList.contains("hidden")).toBe(false);
|
||||
|
||||
document.body.click();
|
||||
|
||||
expect(menu.classList.contains("hidden")).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user