Search code examples
javascriptjqueryfocusoutjquery-focusout

Change focus between web inputs


In a JavaScript/jQuery web context, having:

  • Two form text input fields, A and B, that are enabled
  • The input fields should be disabled if none of them has focus

I.e. by jQuery's focusout function to check when both A and B loses focus works fine, but when A loses focus to B (tab or by selecting B), I am not able to check if B as gained focus yet, since A's focusouts before the focus change is completed.

How can I check by a focusout or equal that both A and B has lost focus when switching between the input fields?

Example:

Disables the input fields when both looses focus, but unfortinately also when switching between them - which is not the intention.

$('input').focusout(function() {
    if ($(':focus').length === 0) { // does not count the other input yet
        $("input").prop('disabled', true);
    }
});

https://jsfiddle.net/hbypowv4/


Solution

  • You can use MouseEvent.relatedTarget to check if A loses focus to B

    The MouseEvent.relatedTarget read-only property is the secondary target for the event, if there is one

    https://jsfiddle.net/hbypowv4/2/