0

Please look at the following code.

var $myInput = $('#myInput'); //select the <input> element

$myInput.on('focus', function(){
   console.log('Input focused');
})

Now if I execute the following two lines in IE:

$myInput.trigger('focus');
console.log('Done');

.. the output will be :

Done
Input Focused

This is because, in IE, the triggered events execute asynchronously. But it's the other way around in all the other browsers. Is there any workaround than using the triggerHandle() or manually calling the event handler function?

Charlie
  • 22,886
  • 11
  • 59
  • 90
  • You mean that the order is not guaranteed in other browsers too? – Charlie Oct 13 '17 at 08:30
  • 2
    Possible duplicate of [How to order events bound with jQuery](https://stackoverflow.com/questions/290254/how-to-order-events-bound-with-jquery) – Liam Oct 13 '17 at 08:32

2 Answers2

2

No. There's no way to reliably guarantee the order. The workaround is to not fake events. Place the logic that's executed within the focus event in its own function, then call that directly.

var $myInput = $('#myInput');    
$myInput.on('focus', function() {
  foo();
})    

foo();
console.log('Done');

function foo() {
  console.log('foo');
}
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • You mean that the order is not guaranteed in other browsers too? – Charlie Oct 13 '17 at 08:30
  • 2
    That's correct. It's not guaranteed, but their JS implementation is fast enough that you can normally get away with it. IEs is not. – Rory McCrossan Oct 13 '17 at 08:31
  • Yes, The order is not guaranteed. You can saw this in the follow question: https://stackoverflow.com/questions/46707989/how-trigger-element-event-synchronously-in-ie/46708210#46708210 – Mihai Alexandru-Ionut Oct 13 '17 at 08:39
0

Although JS could be seen as single-threaded to scripts, the browser architecture handles things differently. One example is, in some systems, the window.onresize code can fire while you are in the middle executing a script.

Here is is an answer which gives some insight towards that end.

So, when you trigger an event, the browser puts it in the event queue which runs parallel (?the cited answer have some proof for this).

What happens then is:

  1. IE is so slow that event loop gets executed after the current code segment is done with.

  2. Other browsers are fast enough that the even in the loop gets executed immediately.

However, all these imply that there is no guaranteed way to conclude which part of the code will preside the other when you trigger an event through code.

Community
  • 1
  • 1
Charlie
  • 22,886
  • 11
  • 59
  • 90