![Firefox logo](https://assets-prod.sumo.prod.webservices.mozgcp.net/media/uploads/products/2020-04-14-08-36-13-8dda6f.png)
Why does https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/autofocus not work?
In https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/autofocus, the browser compatibility box says that autofocus is supported by Firefox, Safari and Chrome. But when I use it, it only works in Chrome. I understand that this problem can easily be solved by .focus() but I just feel that the documentation is misleading.
All Replies (3)
Can you link to an example where it isn't working?
Here's a very simplified test case: https://www.jeffersonscher.com/res/autofocus-select.html
I think I understand my problem. I didn't read the docs clearly enough. It is meant for "select" elements. I was using it on a text field. Here's an example of my code: document.getElementById("name").autofocus=true; It's selecting a text field with the Id of name. This works only in Chrome though.
I don't think it's a problem with input vs. select. I think the MDN article says that Firefox only follows the autofocus attribute on page load. Setting it after page load in your script may well set the attribute, but that comes too late, Firefox ignores it at that point.
Perhaps if you are creating a new DOM element and you set the attribute before using appendChild or insertBefore to add the element to the page, then Firefox might follow it when it is added to the DOM. I haven't tested that.
But the traditional focus() method probably is what you need.