Home > Enterprise >  `onblur` on `input` is triggered when user clicks on link, how to prevent it?
`onblur` on `input` is triggered when user clicks on link, how to prevent it?

Time:08-09

I have a form with input component.
I want to check if user typed proper email so I use onblur event to check if.
I also have an a html element, when user clicks it, it should skip the whole form checking and open another url.

Problem is: the onblur of the input is triggered, which is not intended.

How can I NOT handle onblur of the input when user click on the a element?

Thank you!

CodePudding user response:

For example, something crude like this:

<input id="input">
<a href="#" id="dontMindMe">Link</a>
document.querySelector("#input").addEventListener(click, event => {
    if (event.target.id !== "dontMindMe" {
        doStuff();
    }
});

CodePudding user response:

If I get it, you want to process onBlur everytime, except when clicked on link?

There will always be onBlur before click on link, but you can wrap your logic with

const onBlur = () => {
    const timeoutId = setTimeout(() => { ...doStuff... });
}

Then in link's onClick clearTimeout(timeoutId). You would probably save timeoutId in useRef.

  • Related