Home

Awesome

##ember-autofocus 0.0.3

Automatically focus on an input field upon page load in Ember

// myView.handlebars
   :
{{ input autofocus="true" }}
   :
{{ autofocus }}
{# end of file #}

Motivation

Setting the keyboard focus on a specific input element is a quite standard UI behaviour but rather tedious to accomplish in Ember.

Gladly, there’s this very useful recipe on the Ember web site on how you’re supposed to do that; basically, you set the focus after the didInsertElement Ember event fires - done! This, this and this Stackoverflow answer propose similar techniques.

Unfortunately, the proposed solutions require subclassing into your own Views, which I do not like so much for various reasons.

Thus, Change!

Solution

ember-autofocus bundles Ember's proposed technique into a neat package and adds a few improvements along the way:

How it works

Installing

Bower

bower install ember-autofocus

In your index.html:

<script type="text/javascript" src="bower_components/ember-autofocus/dist/ember-autofocus.min.js)"></script>

Usage

Most compatible (recommended)

// myView.handlebars
   :
{{ input autofocus="autofocus"}}
   :
{{ autofocus }}
{# end of file #}

Laziest

Autofocus on the first <input> element.

// myView.handlebars
   :
{{ input }}
   :
{{ autofocus }}
{# end of file #}

Most Sophisticated

Use a CSS selector to autofocus on a specific element.

// myView.handlebars
   :
{{ autofocus on='#my-special-element .my-unique-class' }}
{# end of file #}

Automatic scrolling in HTML5

Safari, Chrome, Firefox and possibly other HTML5 browsers that support autofocus natively will set the keyboard focus to the specified field and will automatically scroll there. In my use case, that's not wanted because the input field may be below the screen fold and automatically scrolling there is not what users would expect.

You can choose whether or not you want the scrolling behavior with the scrolling option:

scrolling = "true|false"

The default is false, which means that the browser will not scroll to the autofocus element.

// myView.handlebars
   :
{{ autofocus scrolling="true" }}
{# end of file #}

Caveats

Thanks

I have found some very valuable advice during my research which I have built into ember-autofocus:

License

Copyright (c) 2014 Andreas Pizsa. Released under an MIT license.


Made with ❤ in Vienna, Austria.