Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meteor.js - setting focus to form input field upon template refactor

Tags:

jquery

meteor

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!

like image 231
jd1138 Avatar asked Jun 24 '15 17:06

jd1138


2 Answers

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();
    });
  }
});
like image 138
saimeunt Avatar answered Oct 01 '22 07:10

saimeunt


Try adding autofocus

<input name="name" type="text" id="mainInput" autofocus>
like image 32
depperm Avatar answered Oct 01 '22 09:10

depperm