TLDR
tab
A quick fix (untested) should be to defer the call to focus() via
focus()
setTimeout(function() { ... }, 0);
until after the event handler has terminated.
However, it is possible to make it work without such a hack; jQuery-free example code: