Last active
October 6, 2023 09:46
-
-
Save chrisjhoughton/7890303 to your computer and use it in GitHub Desktop.
Wait for an element to exist on the page with jQuery
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var waitForEl = function(selector, callback) { | |
if (jQuery(selector).length) { | |
callback(); | |
} else { | |
setTimeout(function() { | |
waitForEl(selector, callback); | |
}, 100); | |
} | |
}; | |
waitForEl(selector, function() { | |
// work the magic | |
}); |
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
Works very well! Thank you! You are a life saver to my project