Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Internet explorer focus before addEventListener triggers focus?

Today I stumbled upon a weird Internet Explorer quirk. I call the focus function of the element and AFTER that I bind the event listener. In all browsers it executes chronological, in IE however it does not.

I have this piece of code:

var t = document.getElementById('focusable');
t.focus();
t.addEventListener('focus', function() {
  alert('This should only happen after the second focus.');
});
<input id="focusable">

My question is:
Why does this happen? and how can I solve it without a setTimeout(fn,0); hack.

Note: I'm using IE11

like image 764
A1rPun Avatar asked Dec 09 '25 21:12

A1rPun


1 Answers

Why does this happen?

Presumably because IE doesn't actually give the element focus until the JavaScript thread has yielded back to the browser.

and how can I solve it without a setTimeout(fn,0); hack.

Using setTimeout seems like the right thing in this situation, not a hack. But not if it doesn't work. :-)

I hate to say it, but it sounds like you probably need a flag and to intentionally ensure the first focus fires your handler:

(function() {
  var flag = false;
  var t = document.getElementById('focusable');
  t.blur();
  t.addEventListener('focus', function() {
    if (!flag) {
      flag = true;
    } else {
      console.log('This should only happen after the second focus.');
    }
  }, false);
  t.focus();
})();
<input id="focusable">
like image 149
T.J. Crowder Avatar answered Dec 11 '25 09:12

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!