If have this piece of code that I want it to keep looping until a div with an id of “myDiv” exists and if it does exist, stop the while loop. But with my current code it just goes into a never ending loop which makes firefox eventually force quit the script.
I need it to loop becuase sometimes that div may not exist so I need something to keep checking if it exists, and when it does exist, execute the alert.
Thanks in advance, let me know if I did not explain this clearly.
<script type="text/javascript">
var p = 1;
while (p == 1) {
if (document.getElementById('myDiv') != null) {
alert(p);
p++;
}
}
</script>
<div id="myDiv"></div>
Just trying to learn so forgive me if this sounds stupid, but why does javascript block the code?
I’ll try to explain why, lets say I have two buttons, button A and Button B, And A div with an id of “myDiv”. When I click Button A it will update mydiv but the update is coming from an ajax request so it could take a second or two to finish, while it is taking its sweet time, if I click on Button B, which needs information from mydiv, it breaks the script becuase at the moment I click on Button B and mydiv is still loading from when I clicked button a, there is no mydiv.
Don’t make a crazy while loop like that. Even if it seems to work ok on your computer and net connection, imagine what’s gonna happen when that loading div hangs around for more than a split second? That loop is killer…
Now’s a good time to start learning about events, event handlers, and event based programming. Javascript heavily uses these.
If you want to be able to queue up some task that should be executed as soon as that div exists, you need to just store the task in a variable(as a function), and then whatever code makes the div exist, has the responsibility to execute any pending tasks.
var pendingTask = null;
if (theDivExists) {
// we can just do it now
alert(5);
} else {
// we cant do it yet, so just put the task to the side for now
// some other code will check this variable
// to see if something is waiting to be done
pendingTask = function() {
alert(5);
};
}
The code that creates the div has the responsibility to check for pendingTask
if (pendingTask != null) {
// call it
pendingTask();
}