I am trying to use focusin
on an element, but it triggers everytime the tab key is pressed on one of its child elements. Is there something like a focusenter
that only triggers once (similar to that of mouseenter
) when one of the child elements is focused?
I am trying to create a focus trap, so when focus enters the div via keyboard it focuses on the first item in the trap. Currently when I press shift+tab it focuses on the last item in the trap instead of the first item. When I enter the trap using only shift it focuses on the first item which is what I want.
document.getElementById('wrapper').addEventListener('focusin', () => {
console.log('here');
});
#wrapper {
display: flex;
gap: 20px;
}
.item {
background: blue;
color: white;
}
.item:focus-visible {
outline: red solid 2px;
outline-offset: 2px;
}
<div id="wrapper">
<a href="" class="item">Item A</a>
<a href="" class="item">Item B</a>
<a href="" class="item">Item C</a>
</div>
2
Answers
Unfortunately, it’s hard to understand what you’re trying to achieve… But I’ll assume you want to be able to focus only on the first element. And if the focus fell on it, it remained there until certain events. So you can add to all elements except the first
tabindex="-1"
. And if you want to prevent the focus from exiting when the keyboard is pressed, handle thekeydown
event. Something like this:You need to invoke stopPropagation method on Event object and use capture