I have an input box that I want to display and set focus on when a button is clicked. The issue is that the input is hidden until said button is clicked, and when I try to set focus, it doesn’t work. I’m assuming it’s because the $.focus()
call happens before the input is rendered.
Non-working example: http://meteorpad.com/pad/ia54Tdabbn8YzzoTe/blockShown
It would be great if there were some way to say “as soon as the content in this {{if}} block is rendered, call $.focus()
on the input”
I would have the {{if}} block depend upon a reactive data source, and wrap the $.focus() function inside of a tracker.autorun function which also contains the same reactive data source that the {{if}} block is responding to.
var someReactiveVariable = ReactiveVar('something');
Template.sometemplate.helpers({
shouldShow: function(){
return someReactiveVariable.get() === 'another thing';
}
});
Template.sometemplate.onRendered({
Tracker.autorun(function () {
if(someReactiveVariable.get() === 'another thing'){
$.focus();
}
});
});
The best pattern to achieve that is to create a separate template for what you want to render within the if block and put your initialization code within the onRender callback of that template.
3 Likes
@serkandurusoy Yeah, that was my thinking too. I just didn’t want to have a separate template for about one line of HTML code. But this seems like the simplest way.
It also pays off later on down the road if/when you find yourself enhancing that piece of template with other functionality or if/when you find out you can actually reuse that snippet over another place in your app
In similar cases, I don’t think of it as “a line of HTML” but as “a unit of interface” and more often than not it’s a unit that could stand in its own, warranting a template.
2 Likes