1
0
Fork 0
mirror of https://github.com/maybe-finance/maybe.git synced 2025-07-21 06:09:38 +02:00
Maybe/app/javascript/controllers/dropdown_controller.js

37 lines
970 B
JavaScript
Raw Normal View History

2024-02-02 09:05:04 -06:00
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 } }
2024-02-02 09:05:04 -06:00
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");
2024-02-02 09:05:04 -06:00
}
hideMenu = () => {
document.removeEventListener("click", this.onDocumentClick);
2024-02-02 09:05:04 -06:00
this.menuTarget.classList.add("hidden");
}
disconnect = () => {
this.hideMenu();
2024-02-02 09:05:04 -06:00
}
onDocumentClick = (e) => {
if (this.menuTarget.contains(e.target) && !this.closeOnClickValue ) {
// user has clicked inside of the dropdown
e.stopPropagation();
return;
}
this.hideMenu();
2024-02-02 09:05:04 -06:00
}
}