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
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"}}
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With