Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent racing between click and blur event ?

my Angular code look like this >

<input type='text' (blur)='saveData()'>
<button (click)='navigateToPage2()'>

Jumping from textbox being focused to the button click, there is racing condition between two events.

Problem is button click gets ignored because the blur event fires first and brings the spinner on the screen while its making server call to save data.

How do I solve this exact problem?

Is there a hack to make click event fire before blur event ?

like image 423
Nick Thakkar Avatar asked Apr 11 '17 20:04

Nick Thakkar


People also ask

How can blurred events be prevented?

If you want to prevent the blur event from being fired, you have to do so when you are inside the mousedown event, you can do so by invoking the method preventDefault() on the event. Click the checkbox, focus input & then click the button, the textfield never loses focus now.

Does tab trigger Onblur?

In browsers, pressing the tab key when a control has focus will move it to the next element in the tab order, causing the current element to lose focus and dispatch a blur event.

What triggers Onblur?

The onblur event occurs when an object loses focus. The onblur event is most often used with form validation code (e.g. when the user leaves a form field). Tip: The onblur event is the opposite of the onfocus event. Tip: The onblur event is similar to the onfocusout event.

What triggers the jQuery blur event?

The blur event occurs when an element loses focus. The blur() method triggers the blur event, or attaches a function to run when a blur event occurs. Tip: This method is often used together with the focus() method.


2 Answers

Instead of such hack to fire click before blur event try following solution :

To understand this better you need to know this Order in which specific event fires:

  1. mouse down
  2. blur
  3. mouse up
  4. click

You can use this order to work in your favor in this case.

Try using Mousedown event instead and that will fire before blur event.

Also, try running this code snippet. It will help you understand the above order

    Type first in text box below and then click button <br/>      <input type='text' onblur="console.log('blur');" />        <button onclick="console.log('click')"         onmouseup="console.log('mouseup')"         onmousedown="console.log('mousedown')" > Type first and then this click button</button>
like image 115
Nick Thakkar Avatar answered Oct 03 '22 01:10

Nick Thakkar


According to this example you can also use e.preventDefault on mouseDown event : https://codepen.io/mudassir0909/pen/eIHqB (he used jquery but it should be the same with an other lib)

like image 22
Sylvain DNS Avatar answered Oct 03 '22 02:10

Sylvain DNS