skip to Main Content

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


  1. 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 the keydown event. Something like this:

    document.getElementById('wrapper').addEventListener('focusin', () => console.log('here'));
    document.getElementById('wrapper').addEventListener('keydown', event => event.preventDefault())
    #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="" tabindex="-1" class="item">Item B</a>
      <a href="" tabindex="-1" class="item">Item C</a>
    </div>
    Login or Signup to reply.
  2. You need to invoke stopPropagation method on Event object and use capture

    document.getElementById('wrapper').addEventListener('focusin', e => { 
    //Logic goes here
    e.stopPropagation(); 
    }, true);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search