6

Is there an event or simple function for a calling a callback once a specific element exists on the page. I am not asking how to check if an element exists.

as an example

$("#item").exists(function(){ });

I ended up using the ready event

 $("#item").ready(function(){ });
Drake
  • 3,851
  • 8
  • 39
  • 48
  • The ready function doesn't seem to work in this way @Drake. See this fiddle as an example: http://jsfiddle.net/YDn5f/ – Jamie Dixon Aug 28 '11 at 08:54

3 Answers3

3

I was having this same problem, so I went ahead and wrote a plugin for it: https://gist.github.com/4200601

$(selector).waitUntilExists(function);

Code:

(function ($) {

/**
* @function
* @property {object} jQuery plugin which runs handler function once specified element is inserted into the DOM
* @param {function} handler A function to execute at the time when the element is inserted
* @param {bool} shouldRunHandlerOnce Optional: if true, handler is unbound after its first invocation
* @example $(selector).waitUntilExists(function);
*/

$.fn.waitUntilExists    = function (handler, shouldRunHandlerOnce, isChild) {
    var found       = 'found';
    var $this       = $(this.selector);
    var $elements   = $this.not(function () { return $(this).data(found); }).each(handler).data(found, true);

    if (!isChild)
    {
        (window.waitUntilExists_Intervals = window.waitUntilExists_Intervals || {})[this.selector] =
            window.setInterval(function () { $this.waitUntilExists(handler, shouldRunHandlerOnce, true); }, 500)
        ;
    }
    else if (shouldRunHandlerOnce && $elements.length)
    {
        window.clearInterval(window.waitUntilExists_Intervals[this.selector]);
    }

    return $this;
}

}(jQuery));
Ryan Lester
  • 2,363
  • 7
  • 25
  • 38
3

The LiveQuery jQuery plugin seems to be what most people are using to solve this problem.

Live Query utilizes the power of jQuery selectors by binding events or firing callbacks for matched elements auto-magically, even after the page has been loaded and the DOM updated.

Here's a quick jsfiddle that I put together to demonstrate this: http://jsfiddle.net/87WZ3/1/

Here's a demo of firing an event each time a div is created and writing out the unique id of the div that was just created: http://jsfiddle.net/87WZ3/2/

Jamie Dixon
  • 53,019
  • 19
  • 125
  • 162
1

Take a look at the .live function. It executes on all current and future elements in the selector.

$('div').live( function() {});

mrtsherman
  • 39,342
  • 23
  • 87
  • 111