I’ve never used setInterval() and I need some advice as I can’t get my head round this. I want to create some kind of event listener.
Say for example I want to check the length of options in a Select Menu however a third party script populates the content of the Select Menu via an Ajax request. Unfortunately I’m not allowed to touch the the third party script so I though about having a function that waits and listens for the content to be added and can then perform it’s tasks.
say I have the following on my web page:
<select size="7" id="cat"> </select>
onload this gets filled with options like this:
<option value="Category 1">Category 1</option>
<option value="Category 2">Category 2</option>
<option value="Category 3">Category 3</option>
<option value="Category 4">Category 4</option>
I was going to add a function that also loads onLoad (or $(document).ready() to be exact) that will listen to the length of the options and if greater than zero we wish to do something (in this example an alert)
function checkLen(){
if($('#cat option').size() > 0){
return true;
}else{
return false;
}
}
function takeDefault(){
var ourInterval = setInterval("checkLen();", 1000);
if(ourInterval == true){
alert("Okay I will do something now");
clearInterval(ourInterval);
}
// Now I will perform some other tasks
}
$(document).ready(function() {
takeDefault();
});
Now this just doesn’t work as I don’t really understand. The if(checkLen == True) condition is only done once and I need this to be done every second until the select menu is populated.
For simplicity I used different elements, but the idea is still the same:
http://jsfiddle.net/suKCp/
For your case this should be something like (untested):