I want to navigate focus between elements in my web application using up or down keys (instead of just Tab and Shift + Tab). I'm able to do this by using the following helpers:
export function focusPrevious(focused, lockParent = false) {
let previousSibling = focused.previousElementSibling;
if (previousSibling == null) {
if (!lockParent) {
focusPrevious(focused.parentElement, lockParent);
return;
}
previousSibling = focused.parentElement.lastElementChild;
}
previousSibling.focus();
}
export function focusNext(focused, lockParent = false) {
let nextSibling = focused.nextElementSibling;
if (nextSibling == null) {
if (!lockParent) {
focusNext(focused.parentElement, lockParent);
return;
}
nextSibling = focused.parentElement.firstElementChild;
}
nextSibling.focus();
}
However, this is problematic. It may end up focusing non-focusable elements, and doesn't navigate cleverly. For example, it may end up focusing a non-focusable text area <div>
. Is there a better solution?