Use keydown event to detect keyboard based clicks

Relying on e.detail is not supported on all OS/browsers
This commit is contained in:
Chris McCord 2021-11-18 22:09:01 -05:00
parent 7d8e1f2ec6
commit 6622f791e0

View file

@ -19,7 +19,7 @@ Hooks.Menu = {
return val return val
}, },
reset(){ reset(){
this.enabled = true this.enabled = false
this.activeClass = this.getAttr("data-active-class") this.activeClass = this.getAttr("data-active-class")
this.deactivate(this.menuItems()) this.deactivate(this.menuItems())
this.activeItem = null this.activeItem = null
@ -30,18 +30,19 @@ Hooks.Menu = {
this.menuItemsContainer = document.querySelector(`[aria-labelledby="${this.el.id}"]`) this.menuItemsContainer = document.querySelector(`[aria-labelledby="${this.el.id}"]`)
this.reset() this.reset()
this.handleKeyDown = (e) => this.onKeyDown(e) this.handleKeyDown = (e) => this.onKeyDown(e)
this.el.addEventListener("keydown", e => {
if((e.key === "Enter" || e.key === " ") && e.currentTarget.isSameNode(this.el)){
this.enabled = true
}
})
this.el.addEventListener("click", e => { this.el.addEventListener("click", e => {
if(!e.currentTarget.isSameNode(this.el)){ return } if(!e.currentTarget.isSameNode(this.el)){ return }
window.addEventListener("keydown", this.handleKeyDown) window.addEventListener("keydown", this.handleKeyDown)
// disable if button clicked and click was not a keyboard event // disable if button clicked and click was not a keyboard event
if(e.detail !== 0){
this.enabled = false
} else {
if(this.enabled){ if(this.enabled){
window.requestAnimationFrame(() => this.activate(0)) window.requestAnimationFrame(() => this.activate(0))
} }
}
}) })
this.menuItemsContainer.addEventListener("phx:hide", () => this.reset()) this.menuItemsContainer.addEventListener("phx:hide", () => this.reset())
}, },