The last example of jQuery\'s focus() documentation states
$(\'#id\').focus()
should make the input focused (active). I can\'t seem to get
Some of the answers here suggest using setTimeout
to delay the process of focusing on the target element. One of them mentions that the target is inside a modal dialog. I cannot comment further on the correctness of the setTimeout
solution without knowing the specific details of where it was used. However, I thought I should provide an answer here to help out people who run into this thread just as I did
The simple fact of the matter is that you cannot focus on an element which is not yet visible. If you run into this problem ensure that the target is actually visible when the attempt to focus it is made. In my own case I was doing something along these lines
$('#elementid').animate({left:0,duration:'slow'});
$('#elementid').focus();
This did not work. I only realized what was going on when I executed $('#elementid').focus()` from the console which did work. The difference - in my code above the target there is no certainty that the target will infact be visible since the animation may not be complete. And there lies the clue
$('#elementid').animate({left:0,duration:'slow',complete:focusFunction});
function focusFunction(){$('#elementid').focus();}
works just as expected. I too had initially put in a setTimeout
solution and it worked too. However, an arbitrarily chosen timeout is bound to break the solution sooner or later depending on how slowly the host device goes about the process of ensuring that the target element is visible.
I also had this problem. The solution that worked in my case was using the tabindex property on the HTML element.
I was using ng-repeat
for some li elements inside a list and I was not able to bring focus to the first li using .focus(), so I simply added the tabindex attribute to each li during the loop.
so now <li ng-repeat="user in users track by $index" tabindex="{{$index+1}}"></li>
That +1 was index starts from 0. Also make sure that the element is present in DOM before calling the .focus() function
I hope this helps.