Skip to main content

Autofocus In Modals

tldr: For elements inside a Bootstrap modal, use the data-autofocus attribute instead of autofocus.

As the Bootstrap documentation for modals details, setting the autofocus attribute on an element inside a modal will have no effect:

"Due to how HTML5 defines its semantics, the autofocus HTML attribute has no effect in Bootstrap modals. To achieve the same effect, use some custom JavaScript."

Following their advice, PMACS Frontend implements its own custom JavaScript to allow for autofocusing onto an element on modal opening. However, to use this feature, you must set the data-autofocus attribute instead of the HTML5 autofocus attribute. This is because setting the HTML5 autofocus attribute on an element in a modal has some odd side-effects in some browsers. Thus, the recommendation for an element you want to automatically receive focus after the modal is opened is to simply add the data-autofocus attribute.