Reputation: 2012
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
Upvotes: 6
Views: 7281
Reputation: 602
in my case this helps https://github.com/ember-a11y/ember-component-focus
component.coffee
import FocusableComponent from 'ember-component-focus/mixins/focusable-component'
export default Ember.Component.extend FocusableComponent,
actions:
show: () ->
@set 'AddCardMode', true
@focusAfterRender "#1"
template.emblem
if AddCardMode
something input id=1
Upvotes: 0
Reputation: 23322
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.
Upvotes: 5
Reputation: 38832
You can create a component
that wraps the input
field and use the didInsertElement
hook to focus the inner input
:
In the template:
// template.hbs
{{#focus-input}}
{{input type="text"}}
{{/focus-input}}
Your component:
// components/focus-input.js
import Ember from 'ember';
export default Ember.Component.extend({
didInsertElement () {
this.$('input').focus();
}
});
Upvotes: 1
Reputation: 10503
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"}}
Upvotes: 6
Reputation: 1756
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
.
Upvotes: 1