Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

onBlur attached to div getting called while moving from one input element to other present in the same div

So I have a div and inside that div I have two input fields, like:

 <div>
    <input placeholder="Input1"/>
    <input placeholder="Input2"/>
 </div>

I wanted to call certain function whenever user clicks away from that div (not input fields).

So I attached onBlur event for that particular div, by giving it a tabIndex.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<div tabIndex="1" onClick={handleClick} onBlur={handleOnBlur}>

But now the onBlur event is getting triggered whenever I move from one input field to another input field residing in the same div.

I couldn’t understand why this is happening. Also is there any better approach to achieve this sort of functionality.

Codesandbox link to play-around:
https://codesandbox.io/s/tender-carson-9rkj13

>Solution :

By passing in the event as a parameter to your handleOnBlur function, you can make use of currentTarget and relatedTarget properties, and discard events where the relatedTarget (<input>) is a child of the currentTarget (<div>).

For example:

const handleOnBlur = (event) => {
  if (event.currentTarget.contains(event.relatedTarget)) {
    return;
  }
  console.log("On blur for div called, setting false");
  setShowBtn(false);
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading