Reputation: 16847
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
Upvotes: 3
Views: 551
Reputation: 1074989
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 But not if it doesn't work. :-)setTimeout
seems like the right thing in this situation, not a hack.
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">
Upvotes: 2