This is the code I have so far, which at the moment loads the info from the xml file as desired with javascript. I’ve set it to loop 4 times to select 4 images, but these are obviously just the first 4 from the xml file.
Does anyone know the best way to make it randomly select 4 none repeated images from the xml file.
<script>
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","include/photoLibrary.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var x=xmlDoc.getElementsByTagName("photo");
for (i=0; i<4; i++)
{
document.write('<a href="');
document.write(x[i].getElementsByTagName('path')[0].childNodes[0].nodeValue);
document.write('" class="lytebox" data-lyte-options="group:vacation" data-title="');
document.write(x[i].getElementsByTagName('description')[0].childNodes[0].nodeValue);
document.write('"><img src="');
document.write(x[i].getElementsByTagName('thumb')[0].childNodes[0].nodeValue);
document.write('" alt"');
document.write(x[i].getElementsByTagName('title')[0].childNodes[0].nodeValue);
document.write('"/></a>');
}
</script>
If it helps in any way, this is an example of the xml, you’ll see there is an attribute to photo which gives it a unique id.
<gallery>
<photo id="p0001">
<title>Pergola</title>
<path>photos/Pergola.jpg</path>
<thumb>photos/thumbs/Pergola.jpg</thumb>
<description>Please write something here!</description>
<date>
<day>04</day>
<month>04</month>
<year>2006</year>
</date>
</photo>
</gallery>
I’m willing to use php as an alternate to javascript.
First things first. Try not to use
document.writeas this method acts inconstantly when the DOM is ready vs when it is still initializing. Its considered a bad practice.I also recommend using functions to break down the complexity of your code and make it more readable.
You should be aware that XHR objects are not synchronous. You need to wait for the xml data to be retrieved via the
readystatechangeevent.Lastly you don’t have to build strings of html in the browser. The DOM API allows you to create the anchor and image tags as proper nodes which can be attached to the DOM tree.
Hope that helps.
Edit: Fixed three errors. The DOM needs to be loaded before inserting the nodes. XML nodes don’t have innerHTML property. Array.concat does not see DOM NodeList objects as Arrays.