Oscar
Oscar

Reputation: 590

In which order are the "onfocusin" and "onfocusout" events triggered?

Lets say I have two elements: elm_1 and elm_2 and a variable var x = 1

The elements have the following events:

elm_1.addEventListener('focusout', () => x = 1)

elm_2.addEventListener('focusin', () => x = 2)

My question is if I change focus from elm_1 to elm_2, can I be sure which event triggers first? Will x be equal to 1 or 2 after I have changed focus? And I don't mean just in this particular case, I am asking how/if I can be 100% sure of which event is executed first so that regardless of what is inside the functions, I can know what will happen first.

Upvotes: 0

Views: 340

Answers (1)

Alejandro
Alejandro

Reputation: 7819

According to the documentation, you can be sure that focusout always fire on the losing focus element before focusin is raised on the new element. So in your particular case the variable x would be 2 after both events fired.

Source:

https://developer.mozilla.org/en-US/docs/Web/API/FocusEvent#order_of_events

Note that even though some implementations shifted the order of some events, both focusout and focusin are fixed in that order.

Upvotes: 1

Related Questions