1
0
Fork 0
mirror of https://github.com/maybe-finance/maybe.git synced 2025-07-21 22:29:38 +02:00
Maybe/app/javascript/controllers/dropdown_controller.js
Thibaut Gorioux 2181cdd118
Allow event propagation to fix turbo frame update (#575)
* Allow event propagation to fix turbo frame update

* Add setting to dropdown to manage close when open and clicking on it
2024-03-28 13:24:07 -04:00

36 lines
970 B
JavaScript

import { Controller } from "@hotwired/stimulus"
// Connects to data-controller="dropdown"
export default class extends Controller {
static targets = ["menu"]
static values = { closeOnClick: { type: Boolean, default: true } }
toggleMenu = (e) => {
e.stopPropagation(); // Prevent event from closing the menu immediately
this.menuTarget.classList.contains("hidden") ? this.showMenu() : this.hideMenu();
}
showMenu = () => {
document.addEventListener("click", this.onDocumentClick);
this.menuTarget.classList.remove("hidden");
}
hideMenu = () => {
document.removeEventListener("click", this.onDocumentClick);
this.menuTarget.classList.add("hidden");
}
disconnect = () => {
this.hideMenu();
}
onDocumentClick = (e) => {
if (this.menuTarget.contains(e.target) && !this.closeOnClickValue ) {
// user has clicked inside of the dropdown
e.stopPropagation();
return;
}
this.hideMenu();
}
}