Home > Mobile >  How to detect focus out on div
How to detect focus out on div

Time:02-06

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>
      </>
  );
}

CodePudding user response:

You can simply take advantage of the Edit happy-roman-bpjpuq

CodePudding user response:

If you only want onBlur to fire when leaving button 2 you can just move the onBlur to button 2

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

);

  • Related