Set focus to field in dynamically loaded DIV

174,724

Solution 1

The load() function is an asynchronous function. You should set the focus after the load() call finishes, that is in the callback function of load(), because otherwise the element you are referring to by #header, does not yet exist. For example:

$("#display").load("?control=msgs", {}, function() { 
  $('#header').focus();
}); 

I had issues myself even with this solution, so i did a setTimeout in the callback and set the focus in the timeout to make /really/ sure the element exists.

Solution 2

Have you tried simply selecting by Id?

$("#header").focus();

Seeing as Ids should be unique, there's no need to have a more specific selector.

Solution 3

Yes, this happens when manipulating an element which doesn't exist yet (a few contributors here also made a good point with the unique ID). I ran into a similar issue. I also need to pass an argument to the function manipulating the element soon to be rendered.

The solution checked off here didn't help me. Finally I found one that worked right out of the box. And it's very pretty, too - a callback.

Instead of:

$( '#header' ).focus();
or the tempting:
setTimeout( $( '#header' ).focus(), 500 );

Try this:

setTimeout( function() { $( '#header' ).focus() }, 500 );

In my code, testing passing the argument, this didn't work, the timeout was ignored:

setTimeout( alert( 'Hello, '+name ), 1000 );

This works, the timeout ticks:

setTimeout( function() { alert( 'Hello, '+name ) }, 1000 );

It sucks that w3schools doesn't mention it.

Credits go to: makemineatriple.com.

Hopefully, this helps somebody who comes here.

Solution 4

If

$("#header").focus();

is not working then is there another element on your page with the id of header?

Use firebug to run $("#header") and see what it returns.

Solution 5

As Omu pointed out, you must set the focus in a document ready function. jQuery provides it for you. And do select on an id. For example, if you have a login page:

$(function() { $("#login-user-name").focus(); }); // jQuery rocks!
Share:
174,724
Ashraf Tawfeeq
Author by

Ashraf Tawfeeq

Updated on February 19, 2021

Comments

  • Ashraf Tawfeeq
    Ashraf Tawfeeq about 3 years

    What is the proper method to set the focus to a specific field within a dynamically loaded DIV?

    $("#display").load("?control=msgs"); // loads the HTML into the DIV
    $('#display').fadeIn("fast"); // display it
    $("tex#header").focus();          // ?? neither that
    $("input#header").focus();        // ?? nor that
    $('#display', '#header').focus()  // ?? nor that
    $("#header").focus();             // ?? nor that works
    

    The following HTML is fetched into the display DIV:

    <div id="display">
    <form id="newHeaderForm" class="dataform" action="/" method="post">
        <input id="to" type="hidden" value="22" name="to"/>
        <dl>
            <dt>Header</dt>
            <dd>
                <input id="header" class="large" type="text" name="header" value="" maxlength="128"/>
            </dd>
     </form>
     </div>
    

    Many, many thanks!

  • Nick
    Nick over 10 years
    The setTimeout seemingly helps even when the element well and truly exists before the invocation of .focus(). The value of 500 is probably overblown, though. Works fine for me with 10 :)
  • EleventyOne
    EleventyOne over 10 years
    I keep seeing solutions like this in regards to tricky scenarios involving the DOM and being "ready". Is there simply no alternative to calling setTimeout for an arbitrary amount of time and hoping that it's enough? It seems to me that such an approach is bound to fail intermittently. This issue was raised recently in a question of mine: stackoverflow.com/questions/21191336/…
  • Michel
    Michel about 8 years
    Timeout function also present in Angular. Other syntax, but same solution. Thanks for setting me on the right track with the timeout.$timeout(function () { $window.document.getElementById('name').focus(); });
  • Stephen Leake
    Stephen Leake almost 6 years
    The proper amount of time in the Timeout is 0; the purpose is to schedule the 'focus()' code to run immediately after the <div> creation code completes. See developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop