Skip to content

Commit

Permalink
add closeOnEscape option using value API
Browse files Browse the repository at this point in the history
  • Loading branch information
adrienpoly committed Oct 25, 2023
1 parent 63f4731 commit d0d5c90
Showing 1 changed file with 11 additions and 1 deletion.
12 changes: 11 additions & 1 deletion src/dropdown.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@ import { transition } from './transition'

export default class extends Controller {
static targets = ['menu', 'button', 'menuItem']
static values = { open: { type: Boolean, default: false } }
static values = {
open: { type: Boolean, default: false },
closeOnEscape: { type: Boolean, default: true },
}

// lifecycle
connect() {
Expand All @@ -30,9 +33,15 @@ export default class extends Controller {
}

hide(event) {
// if the event is a click and the target is not inside the dropdown, then close it
if (event.target.nodeType && this.element.contains(event.target) === false && this.openValue) {
this.openValue = false
}

// if the event is a keydown and the key is escape, then close it
if (this.closeOnEscapeValue && event.key === 'Escape' && this.openValue) {
this.openValue = false
}
}

toggle() {
Expand Down Expand Up @@ -76,6 +85,7 @@ export default class extends Controller {
actions.push('click@window->dropdown#hide')
actions.push('keydown.up->dropdown#previousItem')
actions.push('keydown.down->dropdown#nextItem')
actions.push('keydown.esc->dropdown#hide')
this.element.dataset.action = [...new Set(actions)].join(' ')
}
}

0 comments on commit d0d5c90

Please sign in to comment.