Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect focus out on div

I am working on accessibility, so I am testing my app using TAB key. I would like to do something when following div element loses focus.

So in my imagination this onBlur function should only fire when I would click TAB key on button 2 and move to button 3. But this onBlur is call on every TAB click in inside this div. Why this is happening?

What should I do to fire function only when I will be outside of this div. So after click TAB key on button 2 and move to button 3, this function should be fired

export default function App() {
  return (
    <>
      <div onBlur={() => console.log('Blur')} style={{ padding: '20px', border: '1px solid #000'}} tabIndex={0}>
        <button>1</button>
        <button>2</button>
      </div>
      <button>3</button>
      </>
  );
}

like image 699
LaysDev Avatar asked Oct 16 '25 14:10

LaysDev


1 Answers

You can simply take advantage of the e.relatedTarget that is available in the onBlur callback to detect if:

  1. The related target is the current target <div> itself, or
  2. The related target is a descendant of the current target <div> by using the Node.contains method

If neither conditions are met, then you conditionally invoke the necessary logic:

<div
  onBlur={(e) => {
    if (
      e.relatedTarget !== e.currentTarget &&
      !e.currentTarget.contains(e.relatedTarget)
    ) {
      console.log("Blur");
    }
  }}
  tabIndex={0}
>
  {/* Content here */}
</div>

I have made a proof-of-concept Codesandbox to demonstrate the code above, but I've swapped out the <button> with <input> just for a more visual test:

Edit happy-roman-bpjpuq

like image 67
Terry Avatar answered Oct 19 '25 03:10

Terry