What are some reasons for jquery .focus() not working?

dngoo picture dngoo · Mar 7, 2012 · Viewed 109.7k times · Source

Some thoughts are that the ELEMENT_ID.focus() is inside divs that are hidden at certain times.

This should be an easy problem to solve -- but I'm struggling :(

***code works fine -- the text field isn't being focused on upon page loading up.

STEP1 [SOLVED] JAVASCRIPT:

$("#goal-input").focus();

$('#goal-input').keypress(function(event){
 var keycode = (event.keyCode ? event.keyCode : event.which);
  if(keycode == '13') {
etc, etc, etc
}

HTML

<input type="text" id="goal-input" name="goal" />

[STEP2] JAVASCRIPT:

 if (goal) {
          step1.fadeOut('fast', function() {
          step1.hide();
          step2.fadeIn('fast');

etc, etc

HTML:

  <div id="step-2">
        <div class="notifications">
        </div>
        <input type="text" id="name"   name="name" placeholder="Name" />
               <script type="text/javascript">
              $(function(){
              $("#name").focus();
              });
            </script>

Why doesn't step 2 work? :(

Answer

Nick F picture Nick F · Nov 5, 2014

I had problems triggering focus on an element (a form input) that was transitioning into the page. I found it was fixable by invoking the focus event from inside a setTimeout with no delay on it. As I understand it (from, eg. this answer), this delays the function until the current execution queue finishes, so in this case it delays the focus event until the transition has completed.

setTimeout(function(){
    $('#goal-input').focus();
});