Call a function after an element has been created (jQuery)

Why do you need to call a function after creating an element? Sometimes this is needed for a DOM element created outside of your own script. For example, element created by a different js library or an event outside of your direct control.

For such scenarios, I always set an interval which checks periodically whether the target element exists. When the function finds an element, the interval deletes itself. After that runs a callback function.

For this, I have a predefined function which I reuse:

function runAfterElementExists(jquery_selector,callback){
     var checker = window.setInterval(function() {
     //if one or more elements have been yielded by jquery
     //using this selector
    if ($(jquery_selector).length) {

        //stop checking for the existence of this element
        clearInterval(checker);

        //call the passed in function via the parameter above
        callback();
    }}, 200); //I usually check 5 times per second
}

//this is an example place in your code where you would like to
//start checking whether the target element exists
//I have used a class below, but you can use any jQuery selector

runAfterElementExists(".targetElementClass", function() {
    //any code here will run after the element is found to exist
    //and the interval has been deleted
});