Firefox 63 - .focus() is not firing "focus" event for text input

Viewed 498

Here's a codepen to demonstrate what I'm seeing: https://codepen.io/anon/pen/zMvxPy

HTML:

<input type="text" />

JS:

$('input').on('focus', () => {
  console.log('focused...')
});

$('input').focus();

On Chrome, the text input will receive focus and the "focus" event is fired. On Firefox (63.0.1), the text input is not focused and the focus event is not fired.

You can, however, click on the text input and the "focus" event will fire properly.

Any explanations as to why the .focus() method isn't firing the "focus" event in Firefox...?

Note: I'm aware that calling .focus() works via something like a button click (as in https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus#Focus_on_a_text_field) but this example is for calling .focus() during the initial page load.

1 Answers

For anyone else who encounters this, it turns out I had the Firefox dev tools open, and Firefox focuses THAT on page load rather than any items that have .focus() called during the initial render.

A couple observations:

  1. This behavior is also seen in web editors such as CodePen or StackBlitz. Firefox prioritizes focusing the editor pane at the expense of any initial .focus() calls in the code itself.
  2. In the case of an Angular app, even calling .focus() in ngAfterViewInit() gets overridden by Firefox's initial focus on the dev console.
    • For example, try opening https://angular-77iyz4.stackblitz.io in Firefox with and without the dev tools open. The text input will only be focused if the dev tools are closed. In Chrome it won't matter.
Related