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>
</>
);
}
You can simply take advantage of the e.relatedTarget
that is available in the onBlur
callback to detect if:
<div>
itself, or<div>
by using the Node.contains
methodIf 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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With