javascripthtmlreactjsdom-eventsonblur

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.

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