jQuery: Wait until element appears

Caporegime
Joined
18 Oct 2002
Posts
29,493
Location
Back in East London
Hi folks,

We're using jQuery.autocomplete() on a text box, and in the case where a user blur()s the text box before the auto-complete menu has appeared, I want it to auto-select the first one. The simplest method for this seems to be to click() the first element in the menu.

However, the users are blur()ing the textbox before the menu has appeared, so I'd like to somehow register an event to click() the menu even if they are focus()ed on another element in the page.

As you may be able to tell, $(document).ready() is no good at this time, and I can't use $(menuSelector).ready() because I don't want to fire this click() every time the menu appears (some users will wait for the menu to select one themselves.)

So, in short, how do I wait for an element to appear using jQuery?

I'm hoping to achieve something like this:

Code:
$("#textbox").blur(function () {
  $(this).autocomplete("search"); // invokes the autocompleter with the current value of the text box
  $(".ui-menu-item:first a").ready(function () {
    $(this).click();
  });
});
But this tries fires the click long before the menu is on the page.
 
Would it not be easier to bypass the autocomplete, and send an ajax request to the source of the autocomplete, then fill the box with the first result back?
 
Back
Top Bottom