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 ?
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.
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.
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.
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.
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:
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>
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)
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