8

I want to show an input element that is hidden, and focus it.

Component code:

<aura:component >
    <div>
        <input aura:id="input" class="hidden"/>
        <button onclick="{!c.toggleAndFocus}">Toggle and focus!</button>
        <button onclick="{!c.focus}">Focus!</button>
    </div>
</aura:component>

Controller:

({
    toggleAndFocus : function(cmp, event, helper) {
        var input = cmp.find("input");
        $A.util.toggleClass(input, "hidden");
        input.getElement().focus();
    },

    focus : function(cmp, event, helper) {
        var input = cmp.find("input").getElement().focus();
    }
})

And the hidden CSS class just applies display: none.

Pressing the "Toggle and focus!" button toggles the visibility of the input as expected. However, it doesn't focus the input after showing it. Pressing the "Focus!" button when the input is shown focusses the input as expected.

How can I make this "Toggle and focus!" button focus the input after showing it?

3
  • 4
    Could you try setting a timeout before the focus? I think I encountered something similar and setting a timeout did the trick in focusing.
    – akcorp2003
    Jan 11, 2017 at 22:48
  • I thought about this, and just tried it. It does work, I was just hoping there was a cleaner way - but might be stuck with it
    – nicstella
    Jan 12, 2017 at 0:00
  • 3
    @nicstella it has to do with the rendering life cycle of Aura. The elements are not actually updated until the function returns, so you need a callback afterwards.
    – sfdcfox
    Jan 12, 2017 at 0:08

1 Answer 1

1

If your focus() function works, why don't you call it in your toggleAndFocus function?

Just move your focus() function to your helper

e.g.:

Controller:

toggleAndFocus : function(cmp, event, helper) {
    var input = cmp.find("input");
    $A.util.toggleClass(input, "hidden");
    helper.focus(cmp);
}

Helper:

focus : function(cmp) {
    var input = cmp.find("input").getElement().focus();
}

If you want to call your focus function from a component handler, you need a controller function that passed through to the helper.

E.g.

Controller:

focus: function(cmp, event, helper){
    helper.focus(cmp)
}
1
  • It works when the element is already visible, not after toggling it to visible. Sounds like timeouts are the only way to do this, see the comments on the question if interested
    – nicstella
    Jan 12, 2017 at 20:22

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .