HTML's autofocus
attribute focuses an element on the first occurrence of the attribute. But, does nothing on subsequent renders of the same element.
This addon provides an element modifier, which auto focuses the element when it is inserted into the DOM.
ember install @zestia/ember-auto-focus
Add the following to ~/.npmrc
to pull @zestia scoped packages from Github instead of NPM.
@zestia:registry=https://npm.pkg.github.com
//npm.pkg.github.com/:_authToken=<YOUR_GH_TOKEN>
https://zestia.github.io/ember-auto-focus
Optional. This positional argument allows you to auto focus a child element. Useful for occasions when you don't have access to the children.
Example
Optional. This named argument turns off auto focusing. Note that this behaviour can now also be achieved with a conditional modifier (this wasn't always the case).
Optional. Any other named arguments are passed to the focus
method. Some options available include preventScroll
and focusVisible
This modifier has certain benefits over other implementations:
-
It waits until after render, so that in your actions you can be sure
document.activeElement
is as you'd expect (Example). -
It compensates for the fact that child modifiers run their installation before parents in the DOM tree. So nesting
{{autoFocus}}
will work as you would expect. (Example). -
It allows you to differentiate between an element that was focused by a user interacting with it, and an element that was focused programmatically. Through
element.dataset.programmaticallyFocused
. (Example)