Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save KevinBatdorf/6d8bdf7bb16a85c4081b4bf8cd66661d to your computer and use it in GitHub Desktop.
Save KevinBatdorf/6d8bdf7bb16a85c4081b4bf8cd66661d to your computer and use it in GitHub Desktop.
Adds sub menu keyboard up/down navigation (only one level deep) using Alpine.js
Array.from(document.querySelectorAll('.menu-item-has-children')).forEach(menu => {
menu.setAttribute(
'x-data',
`{
usedKeyboard: false,
list: [],
start() {
this.list = this.$el.querySelectorAll("li")
}
}`
)
menu.setAttribute('x-init', 'start()')
menu.setAttribute(
'x-on:keydown.arrow-down.prevent',
`
usedKeyboard = true
let item = list[Array.prototype.indexOf.call(list, document.activeElement.closest('li')) + 1]
if (item) { item.querySelector('a').focus() } else { list[0].querySelector('a').focus() }
`
)
menu.setAttribute(
'x-on:keydown.arrow-up.prevent',
`
usedKeyboard = true
let item = list[Array.prototype.indexOf.call(list, document.activeElement.closest('li')) - 1]
if (item) { item.querySelector('a').focus() } else { list[list.length - 1].querySelector('a').focus() }
`
)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment