Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ember: simple way to set focus in a field

Tags:

ember.js

I am looking for a simple way to set focus into a textfield or textarea. I prefer not to mix Jquery syntax with Ember syntax ... and I prefer not to create seperate views for each textfield or textarea in which I ever want to set the focus.

Any suggestions ?

My textArea field is simply:

{{view Ember.TextArea valueBinding="body" placeholder="body"}}

Thanks Marc

like image 666
cyclomarc Avatar asked Jul 31 '13 09:07

cyclomarc


3 Answers

With new Ember CLI you get this using simply autofocus="autofocus" in template *.hbs

{{input value=text type="text" name="text" placeholder="Enter text" autofocus="autofocus"}}
like image 117
David Douglas Avatar answered Nov 15 '22 11:11

David Douglas


The most straightforward way to set the focus on a TextArea would be the following:

App.FocusTextArea = Ember.TextArea.extend({
  didInsertElement: function() {
    this._super(...arguments);
    this.$().focus();
  }
});

And the whenever you want such a view you can use it like so:

{{view App.FocusTextArea valueBinding="body" placeholder="body"}}

and I prefer not to create seperate views for each textfield or textarea in which I ever want to set the focus.

By creating a custom TextArea view which extends from Ember.TextArea you are not creating each time a new view, you are reusing the custom view with the desired behavior.

Hope it helps.

like image 31
intuitivepixel Avatar answered Nov 15 '22 12:11

intuitivepixel


This little package goes a step further and does this a slight bit more elegantly, directly in the template, without any further coding or subclassing:

<body>
  <!-- all the libraries -->
  <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
  <script src="http://cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.3.0/handlebars.min.js"></script>
  <script src="http://cdnjs.cloudflare.com/ajax/libs/ember.js/1.2.0/ember.min.js"></script>
  <script src="http://rawgithub.com/AndreasPizsa/ember-autofocus/master/dist/ember-autofocus.min.js"></script>
  <!-- your template -->
  <script type="text/x-handlebars">
    Hello, world! {{ input }}
    :
    : more elements here
    :
    {{ autofocus }} {# <<<<< does the magic #}
  </script>
  <!-- your app -->
  <script>
    Ember.Application.create();
  </script>
</body>

You can get it from https://github.com/AndreasPizsa/ember-autofocus or with bower install ember-autofocus.

like image 43
AndreasPizsa Avatar answered Nov 15 '22 10:11

AndreasPizsa