[jquery] $.focus() not working

The last example of jQuery's focus() documentation states

$('#id').focus()

should make the input focused (active). I can't seem to get this working.

Even in the console on this site, I'm trying it for the search box

$('input[name="q"]').focus()

and I'm getting nothing. Any ideas?

This question is related to jquery

The answer is


Had this issue again just now, and believe it or not, all I had to do was close the developer tools. Apparently the Console tab has the focus priority over the page content.


Pro tip. If you want to turn on focus from the dev console then just open the console as a separate window from the options tab. The latest Firefox and Chrome supports this feature.


Found a solution elsewhere on the net...

$('#id').focus();

did not work.

$('#id').get(0).focus();

did work.


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.


For my case I had to specify a tab index (-1 if only focusable via script)

<div tabindex='-1'>
<!-- ... -->
</div>

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 setTimeoutsolution 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.


Make sure the element and its parents are visible. You cannot use focus on hidden elements


In my case, and in case someone else runs into this, I load a form for view, user clicks "Edit" and ajax gets & returns values and updates the form.

Just after this, I tried all of these and none worked except:

setTimeout(function() { $('input[name="q"]').focus() }, 3000);

which I had to change to (due to ajax):

setTimeout(function() { $('input[name="q"]').focus() }, **500**);

and I finally just used $("#q") even though it was an input:

setTimeout(function () { $("#q").focus() }, 500);

I tested code from Chrome's DevTool Console and the focus part not worked. I found out later the issue is only present if i run it from DevTool and if i implement the code to the website it works fine. Actually, the element got focused but the DevTool removed it immediately.


if you use bootstrap + modal, this worked for me :

  $(myModal).modal('toggle');
  $(myModal).on('shown.bs.modal', function() {
    $('#modalSearchBox').focus()
  });

Just in case anybody else stumbles across this question and had the same situation I had - I was trying to set the focus after clicking on another element, yet the focus didn't appear to work. It turns out I just needed an e.preventDefault(); - here's an example:

$('#recipients ul li').mousedown(function(e) {
    // add recipient to list
    ...
    // focus back onto the input
    $('#message_recipient_input').focus();
    // prevent the focus from leaving
    e.preventDefault();
});

This helped:

If you call HTMLElement.focus() from a mousedown event handler, you must call event.preventDefault() to keep the focus from leaving the HTMLElement. Source: https://developer.mozilla.org/en/docs/Web/API/HTMLElement/focus


I realize this is old, but came across it today. None of the answers worked for me, what I did find that worked was setTimeout. I wanted my focus to be placed on the input filed of a modal, using the setTimeout worked. Hope this helps!


Add a delay before focus(). 200 ms is enough

function focusAndCursor(selector){
  var input = $(selector);
  setTimeout(function() {
    // this focus on last character if input isn't empty
    tmp = input.val(); input.focus().val("").blur().focus().val(tmp);
  }, 200);
}

For those with the problem of not working because you used "$(element).show()". I solved it the next way:

 var textbox = $("#otherOption");
 textbox.show("fast", function () {
    textbox[0].focus();
  });

So you dont need a timer, it will execute after the show method is completed.


You can try this id is tries

window.location.hash = '#tries';

ADDITIONAL SOLUTION Had same issue where focus() didn't seem to work but eventually it turned out that what was needed was scrolling to the correct position: