New to Meteor and appreciate any help - have been struggling with this one. So I have a template that is drawn conditionally:
{{#if creating}}
<form class="form-create">
<input name="name" type="text" id="mainInput">
<button type="submit">Submit</button>
<a class="cancel" href="#">Cancel</a>
</form>
{{else}}
<a class="create" href="#">Create</a>
{{/if}}
That works just fine - clicking the anchor link summons the form by way of the "CREATING" session reactive variable, cancel the form summons the anchor again.
My issue is when the Form appears, I'd like to set the input (#mainInput) to focus. Now this code will work if I wire it up to a button or something (it sets the input to focus so I know the jquery works - for example:
"click .focusBtn": function(e, tpl) {
tpl.$("#mainInput").focus();
tpl.$("#mainInput").select(); //might as well select the entire thing too
},
But, I can't get this focus to 'focus' upon a screen redraw from the anchor to the form!
I've tried hooking it up in the session variable (Creating) code - so that everytime creating is changed (console.log I see the Creating switch from true to false, I validate Creating is true, call the focus from that helper block, but no change)
I've also tried a tracker to the session var creating - like this, to no avail, focus isn't achieved:
Tracker.autorun(function () {
var creating = Session.get('creating');
console.log('Autorun is auto-running!');
console.log(creating);
if (creating) {
$('#mainInput').focus(); // I tried documentbyID, etc but nothing
}
});
I realize it might have something to do with Tracker, or maybe there's a "hook" i'm not aware of (I tried rendered template but this seems to only work upon initial creation, one time) I'm reading the guide now, but still new to this and any help / guidance is appreciated. Thanks!
You were on the right track, you just need to use a Tracker.afterFlush
callback registration to execute the focus
call when Meteor had a chance to render the input after the Session
variable was invalidated and the Spacebars {{#if}}
block helper path chosen.
Tracker.autorun(function () {
var creating = Session.get('creating');
if (creating) {
Tracker.afterFlush(function(){
$('#mainInput').focus();
});
}
});
Try adding autofocus
<input name="name" type="text" id="mainInput" 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