Reputation: 196
I want to focus an input box in my template after Session.set("quizStarted", true);
Template.quiz.startQuiz = function(){
return Session.get("quizStarted");
}
startQuizAnimate = function(){
Session.set("quizStarted", true);
$('.answerBox').focus(); //THIS LINE DOES NOT FOCUS
}
Template.quiz.events({
'click #startQuiz' : function(){
startQuizAnimate();
}
}
<template name="quiz">
<button id="startQuiz">Start!</button>
{{#if startQuiz}}
<form class="answer">
// I want to focus this input text
<input type="text" class="answerBox" name="text" placeholder="Type your answer here" />
</form>
{{/if}}
</div>
</template>
The block inside {{#if startQuiz}}
contains the input I want to focus on, but I have to call it after Session.set("quizStarted", true);
finishes rendering. How can I write this with Meteor's best practices?
Upvotes: 1
Views: 99
Reputation: 22696
Use Tracker.afterFlush
to register custom code to be run once every computations currently invalidated have been rerun, in particular the reactive template computation responsible for rerendering the template and insert the form markup after {{#if startQuiz}}
becomes truthy.
function startQuizAnimate(){
Session.set("quizStarted", true);
Tracker.afterFlush(function(){
$('.answerBox').focus();
});
}
Upvotes: 3