From 6622f791e067de3b7b64da7bd72a7a5ac0dc8a4e Mon Sep 17 00:00:00 2001 From: Chris McCord Date: Thu, 18 Nov 2021 22:09:01 -0500 Subject: [PATCH] Use keydown event to detect keyboard based clicks Relying on e.detail is not supported on all OS/browsers --- assets/js/app.js | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/assets/js/app.js b/assets/js/app.js index c03ae55..04aa4b2 100644 --- a/assets/js/app.js +++ b/assets/js/app.js @@ -19,7 +19,7 @@ Hooks.Menu = { return val }, reset(){ - this.enabled = true + this.enabled = false this.activeClass = this.getAttr("data-active-class") this.deactivate(this.menuItems()) this.activeItem = null @@ -30,17 +30,18 @@ Hooks.Menu = { this.menuItemsContainer = document.querySelector(`[aria-labelledby="${this.el.id}"]`) this.reset() 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 => { if(!e.currentTarget.isSameNode(this.el)){ return } window.addEventListener("keydown", this.handleKeyDown) // disable if button clicked and click was not a keyboard event - if(e.detail !== 0){ - this.enabled = false - } else { - if(this.enabled){ - window.requestAnimationFrame(() => this.activate(0)) - } + if(this.enabled){ + window.requestAnimationFrame(() => this.activate(0)) } }) this.menuItemsContainer.addEventListener("phx:hide", () => this.reset())