How to set focus using jQuery on an element that has just appeared

DaFoot picture DaFoot · Feb 17, 2012 · Viewed 52.9k times · Source

I have a document ready block as follows:

$(document).ready(function () {
    $('#addTagLink').click(function () {
        $('#addTagField').show();
        $('#addTagField').val("");
        $('#addTagField').focus();
    });
});

The addTagField is a regular text input that has display:none set by css on page load.

When a user clicks on the addTagLink element the input field is shown correctly but focus doesn't get set to the field as intended.

I figured it must be something to do with the display:none / show() functionality, so changed the $('#addTagField').focus(); to another field $('#name').focus();which worked perfectly.

Can anyone suggest firstly why I see this issue and secondly, how to fix it?

Answer

DaFoot picture DaFoot · Jul 27, 2012

Turns out it was a problem with my element IDs. Oops.