Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery element exists event

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(){ });
like image 937
Drake Avatar asked Aug 28 '11 08:08

Drake


2 Answers

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/

like image 103
Jamie Dixon Avatar answered Nov 03 '22 22:11

Jamie Dixon


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));
like image 45
Ryan Lester Avatar answered Nov 03 '22 20:11

Ryan Lester