I am trying to focus an input element inside of a polymer template every time it stamps its contents. The problem is that I cannot select the input element until the template has loaded. Currently, I am just using setTimeout to focus the input 100ms after the template should load, but I want to know if there is a more elegant solution. Also, the autofocus attribute doesn't work, because the template may un-stamp and re-stamp many times. Right now, my code looks something like this (this is inside a polymer element definition):
Polymer({ // ... showInput: false, makeInputVisible: function() { this.showInput = true; var container = this.$.container; setTimeout(function() { container.querySelector("#input").focus(); }, 100); }, });
<div id="container"> <template if="{{showInput}}"> <input id="input" is="core-input" committedValue="{{inputValue}}" /> </template> </div>
But I would prefer something more like this:
Polymer({ // ... showInput: false, makeInputVisible: function() { this.showInput = true; }, focusInput: function() { this.$.container.querySelector("#input").focus(); }, });
<div id="container"> <template if="{{showInput}}" on-stamp="{{focusInput}}"> <input id="input" is="core-input" committedValue="{{inputValue}}" /> </template> </div>
Any ideas are appreciated.