Bootstrap 5 navbar features dropdown menus that have underlined hotkeys such as a
,n
,s
, and e
.
https://i.sstatic.net/bZOaC1kU.png
<div class="btn-group">
<button type="button" class="btn btn-danger dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
Action
</button>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#"><u>A</u>ction</a></li>
<li><a class="dropdown-item" href="#">A<u>n</u>other action</a></li>
<li><a class="dropdown-item" href="#"><u>S</u>omething else here</a></li>
<li><hr class="dropdown-divider"></li>
<li><a class="dropdown-item" href="#">S<u>e</u>parated link</a></li>
</ul>
</div>
If a key on the keyboard is pressed, how can the corresponding menu item be activated? For instance, when the dropdown menu is open, pressing "A" should act as though the "Action" menu item is clicked.
jsfiddle: https://jsfiddle.net/b6or2s5e/
Handling of left and right arrow keys is already implemented.
How to use left and right arrow keys to navigate in bootstrap navbar
document.addEventListener("DOMContentLoaded", function () {
document.querySelectorAll('.dropdown').forEach(function (el) {
el.addEventListener('shown.bs.dropdown', function () {
document.addEventListener('keydown', function (e) {
const click = new MouseEvent("click", {
bubbles: true,
cancelable: true,
view: window,
})
if (e.key === "ArrowRight") {
const o = getNextSibling(e.target.closest('.dropdown'), '.dropdown')
if (!o) {
document.querySelector('.dropdown-toggle').dispatchEvent(click)
} else {
o.querySelector('.Xdropdown-toggle').dispatchEvent(click)
}
} else if (e.key === "ArrowLeft") {
const o = getPrevSibling(e.target.closest('.dropdown'), '.dropdown')
if (!o) {
const ar = document.querySelectorAll('.dropdown-toggle')
ar[ar.length - 1].dispatchEvent(click)
} else {
o.querySelector('.dropdown-toggle').dispatchEvent(click)
}
}
}, { once: true })
})
})
})
How can hotkey handling be added as well?