[SalesForce] How to use Lightning:input focus on init

Not sure what am i missing here but trying few approaches but still having some issues and it doesn't work so far.

How can I invoke the method focus on a ui input :

cmp

 <lightning:input label="Name" aura:id="itemName" value="{!v.item.Name}"  required="true" />

js

var nameInput = component.find('itemName');
nameInput.focus();

Also tried

component.find('itemName').getElement().focus();

Best Answer

This might just be a matter of dom load timing! There are couple of ways you can make it work.

  1. Adding a timer
  2. Using after renderer

Adding a timer

   window.setTimeout(
            $A.getCallback(function () {
                cmp.find("itemName").focus();
            }), 1
        );

Renderer Approach:

afterRender: function (cmp, helper) {
    this.superAfterRender();
   cmp.find("itemName").focus();
}
Related Topic