File size: 798 Bytes
5010ad7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
static targets = ["button", "menu"]
connect() {
this.boundClickOutside = this.clickOutside.bind(this)
document.addEventListener("click", this.boundClickOutside)
}
disconnect() {
document.removeEventListener("click", this.boundClickOutside)
}
toggle() {
const open = this.menuTarget.classList.toggle("hidden") === false
this.buttonTarget.setAttribute("aria-expanded", open)
if (open) this.menuTarget.focus()
}
clickOutside(event) {
if (!this.element.contains(event.target)) {
this.close()
}
}
close() {
this.menuTarget.classList.add("hidden")
this.buttonTarget.setAttribute("aria-expanded", "false")
this.buttonTarget.focus()
}
}
|