In order to make an prevent an element from taking focus ("non-focusable"), you need to use Javascript to watch for the focus
and prevent the default interaction.
In order to prevent an element from being tabbed to, use tabindex=-1
attribute.
Adding tabindex=-1
will make any element focusable, even div
elements. This means when a user clicks on it, it would likely get a focus outline, depending on the browser..
You would ideally, want this:
/**
* @this {HTMLElement}
* @param {FocusEvent} event
* @return {void}
*/
function preventFocus(event) {
if (event.relatedTarget) {
// Revert focus back to previous blurring element
event.relatedTarget.focus();
} else {
// No previous focus target, blur instead
this.blur();
// Alternatively: event.currentTarget.blur();
}
}
/* ... */
element.setAttribute('tabindex', '-1');
element.addEventListener('focus', preventFocus);
For safe typechecking, you can perform if (event.relatedTarget instanceof HTMLElement)
instead if (event.relatedTarget)
.