2

The problem is that when there is a focus on one #input1, and i try to focus it on #input2 by running

$('#input2').focus();

first runs the focusin event of #input2 then the focusout of the #input1

Why does this happen, why isn't focusout running first?

Please see for an example http://jsfiddle.net/zZZsD/3/ Type in first input 4 symbols

UPDATE: Btw, I've used delegated binding instead of direct for performance reasons,there will be potentially lots of input fields...

Vlad
  • 655
  • 6
  • 12
  • I don't see the problem. When I'm in #input1 and click on #input2, it says "focusout of input1, focusin of input2" so i don't know what you mean... – Ian Jul 12 '12 at 19:59
  • you should not click on #input2, click on #input1 and type 4 symbols in order to trigger focus() – Vlad Jul 12 '12 at 20:04

2 Answers2

1

There's something called Event Hierarchy. It decides what order the events are fired in.

It's important to make a note of this if your case requires one to fire before another.

See this question for more.

Community
  • 1
  • 1
Robin Maben
  • 22,194
  • 16
  • 64
  • 99
1

Probably this is a internal mechanism of jQuery, or even "worse", of Javascript Engine in the browser. If it's important the order, you can use the blur method before the focus.

(function () {
    $('#cont').on('keyup', 'input', function (event) {
        var input = $(this);
        if (input.val().length == 4) {
            input.blur();
            $('#input2').focus();
        }
    });

    $('#cont').on('focus', 'input', function () {
        $('#events').append('focusin of ' + this.id + ' <br>');
    });

    $('#cont').on('blur', 'input', function () {
        $('#events').append('focusout of ' + this.id + ' <br>');
    });

})();

Maybe the navigator check for focused elements when you select another element and unfocus them.

anibalsolon
  • 131
  • 1
  • 3