Let's say I have two input fields.
One has focus, then I click on the other input field.
Is it guaranteed that the blur()
event (of the first element that lost focus) happens before the focus()
event (other element got focus) ?
The blur event fires when an element has lost focus. The main difference between this event and focusout is that focusout bubbles while blur does not. The opposite of blur is focus . This event is not cancelable and does not bubble.
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.
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.
The onfocusout event occurs when an element is about to lose focus.
As of W3C draft DOM3 Events, the specification tells you:
Focus Event Order
The focus events defined in this specification occur in a set order relative to one another. The following is the typical sequence of events when a focus is shifted between elements (this order assumes that no element is initially focused):
> User shifts focus > 1. focusin Sent before first target element receives focus > 2. focus Sent after first target element receives focus > User shifts focus > 3. focusout Sent before first target element loses focus > 4. focusin Sent before second target element receives focus > 5. blur Sent after first target element loses focus > 6. focus Sent after second target element receives focus
Note that the statement that there cannot be two elements with focus is not completely correct; although I am not aware of desktop environments that let two widgets have focus at the same time, the specification lets an implementation decide that:
Other specifications may define a more complex focus model than is described in this specification, including allowing multiple elements to have the current focus.
Also this is worth mention:
A host language may define specific elements which might receive focus, the conditions under which an element may receive focus, the means by which focus may be changed, and the order in which the focus changes. (italic is mine).
However, beware that Chrome does not follow the standard - instead the order is blur, focusout, focus, focusin
. You can test this using this page. Webkit browsers may have the same issue. The focusin
and focusout
events are supported since Firefox 52.
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