I have written a script that is working perfectly except that I wish to add a timed loop. I am new to Javascript and have pounded my head over this for a few days now, I’m hoping an expert can help me….
Also I only need this to work in FireFox!
This script is pulling data from XML. If nothing is found in the XML then the page displays as normal. If something is found, then it creates a pop-up div displaying the information found and plays an audio file.
The pop-up is simply a div with visibility set to hidden if nothing is found in XML set by calling an external CSS stylesheet. If something is found, then it references a separate stylesheet and plays and audio file and changes the div setting visible to true.
I need to somehow add a loop so that this script keeps checking the XML file every 20-30 seconds and if something is found, it will display my hidden DIV and play the audio alert. This script is fully functional except for the fact that I cant get the script to loop without reloading the page.
I want to keep this in the <head> tag as well.
<head>
<script type="text/javascript">
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","xml/SearchRequest-11988N.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
xtotaltickets=xmlDoc.getElementsByTagName("issue")[0].getAttributeNode("total");
totaltickets=xtotaltickets.nodeValue;
ytotaltickets=parseInt(totaltickets);
if (ytotaltickets<1)
{
document.write("<link rel='stylesheet' type='text/css' href='notickets.css'>");
}
else
{
document.write("<link rel='stylesheet' type='text/css' href='newtickets.css'>");
var audioElement = document.createElement('audio');
audioElement.setAttribute('src', 'newticket.ogg');
audioElement.play();
}
</script>
Again, I only need this to work in FireFox!
Put your code in a function and use an interval:
A few other things you need to check:
Make sure that the function can be called several times without creating duplicate contents. In particular, you should check if the elements you need are not already there before creating them.
To make sure the code run at the right time, you might want to listen to the body
onloadevent. Also consider using jQuery as it will make the code easier to write and maintain.