Call a function after an element has been created

Sometimes this is needed for a DOM element created/loaded outside of your own script, either 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 and if this is true, the interval deletes itself and 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
});

Leave a Comment

Your email address will not be published. Required fields are marked *