README
@zestia/ember-auto-focus
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.
Installation
ember install @zestia/ember-auto-focus
Demo
https://zestia.github.io/ember-auto-focus/
Example
{{#if this.showField}}
<input {{auto-focus}} />
{{/if}}
Alternatively, you can pass in a selector:
<div {{auto-focus '.my-child'}}>
<div class='my-child' tabindex='0'></div>
</div>
You can set disabled to true to prevent autofocusing:
<div {{auto-focus disabled=this.shouldAutoFocus}} tabindex='0'>
...
</div>
Notes
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
{{auto-focus}}
would not work as you might expect. (Example).
Differentiating between user focus and programmatic focus
Sometimes it's useful to know whether the element that received focus, did so via a user interacting with it, or by your code.
This addon sets a temporary data attribute on the element being focused. element.dataset.programmaticallyFocused
which will be true if focused by this addon, and false if focused by the user using your app.