Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If selector exists - run code else repeat check

I'm trying to check if a selector exists, if it does I would like it to run some code, if it doesn't I would like it to repeat the check.

The reason I want to do this is because I know an element WILL exist, but I will not know when.

Something like this:

if ($(.element).length ) {
    // Do something
}else{
//check again
});

Any ideas?

like image 523
MoDFoX Avatar asked Dec 05 '22 20:12

MoDFoX


1 Answers

var interval = setInterval(function () {
    if ($(".youtube5player").length) {
        clearInterval(interval);
        // Do stuff
    }
}, 100);

What this does is use setInterval to perform a check approximately every 100 ms to see if your selector returns any results. If it does, the interval is cleared and the code will not run again.

Example: http://jsfiddle.net/rBdFP/

like image 123
Andrew Whitaker Avatar answered Dec 08 '22 15:12

Andrew Whitaker