Skip to content

Instantly share code, notes, and snippets.

@chrisjhoughton
Last active October 6, 2023 09:46
Show Gist options
  • Save chrisjhoughton/7890303 to your computer and use it in GitHub Desktop.
Save chrisjhoughton/7890303 to your computer and use it in GitHub Desktop.
Wait for an element to exist on the page with jQuery
var waitForEl = function(selector, callback) {
if (jQuery(selector).length) {
callback();
} else {
setTimeout(function() {
waitForEl(selector, callback);
}, 100);
}
};
waitForEl(selector, function() {
// work the magic
});
@schroef
Copy link

schroef commented Dec 18, 2020

Thanks for making the example! I got one of the examples working, by declaring the bar for the missing selector in each loop. Otherwise it won't work.

@jackdeguest
Copy link

I prefer using a timeout value, so I modified the proposed answer as follows:
This will time out by default after 1 second, or never if a value of 0 is provided.
You can see a codepen here.

var waitForElement = function( selector, callback, interval, timeout )
{
    if( parseInt( timeout ) !== 0 )
    {
        timeout = !isNaN(parseInt(timeout)) || 1000;
    }
    interval = !isNaN(parseInt(interval)) || 100;
    var time = 0;
    var poll = setInterval(function()
    {
        var el = $(selector);
        if( typeof( timeout ) !== 'undefined' && time >= timeout )
        {
            clearInterval( poll );
            return;
        }
        // Try again
        else if( el.length < 1 )
        {
            time += interval;
            return;
        }
        clearInterval( poll );
        callback( el );
    }, interval);
};

@jatieu
Copy link

jatieu commented Dec 27, 2021

View short and full

//Check
let check = (e, m, t, c) => { //(element, max, timeout, callback)
    let i = +m,
    loop = () => { $(e).length ? c() : --i && setTimeout(() => { loop() }, t) }
    loop()
},            
//Process
myFunc = () => { //Do something }
//Usage
check("element", 30, 500, myFunc)

@michaelyeg
Copy link

Works very well! Thank you! You are a life saver to my project

@AMDarter
Copy link

AMDarter commented Mar 1, 2022

Thank you!
I set maxTimes to 100. After 100 tries, it will stop.

jQuery(document).ready(function () {
    var selector = '#element';
  
    var waitForEl = function (selector, callback, maxTimes = false) {
      if (jQuery(selector).length) {
        callback();
      } else {
        if (maxTimes === false || maxTimes > 0) {
          maxTimes != false && maxTimes--;
          setTimeout(function () {
            waitForEl(selector, callback, maxTimes);
          }, 100);
        }
      }
    };
  
    waitForEl(selector, function () {
        jQuery(selector); // do something with selector
    }, 100);
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment