Dynamically populating a JavaScript image slideshow
A pesky problem with JavaScript slideshows it that you need to manually
specify the images to display inside the script. If you have many images,
this can quickly drive you up the wall. How about automating the process
through PHP, by getting it to retrieve the file names of all images and
passing it to your JavaScript slideshow to play around with?
Lets get straight to it, by creating a PHP script that gets
the file names of all images inside the directory the script is placed in,
and return them as a JavaScript array:
<?
//PHP SCRIPT: getimages.php
Header("content-type: application/x-javascript");
//This function gets the file names of all images in the current directory
//and ouputs them as a JavaScript array
function returnimages($dirname=".") {
$pattern="(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$)"; //valid image extensions
$files = array();
$curimage=0;
if($handle = opendir($dirname)) {
while(false !== ($file = readdir($handle))){
if(eregi($pattern, $file)){ //if this file is a valid image
//Output it as a JavaScript array element
echo 'galleryarray['.$curimage.']="'.$file .'";';
$curimage++;
}
}
closedir($handle);
}
return($files);
}
echo 'var galleryarray=new Array();'; //Define array in JavaScript
returnimages() //Output the array elements containing the image file names
?>
This script will grab the file names of every image in a directory (based
on its extension) and output them as JavaScript array elements:
var galleryarray=new Array();
galleryarray[0]='dog.gif'
galleryarray[1]='cat.gif'
galleryarray[2]='person.gif'
where "dog.gif", "cat.gif" etc are the file names of the images inside
the directory. Now that the tedious part is taken care of by PHP, we can go
ahead and create a JavaScript slideshow script that uses this array to
display all images inside the directory!
<script src="pics/getimages.php"></script>
<script type="text/javascript">
var curimg=0
function rotateimages(){
document.getElementById("slideshow").setAttribute("src", "pics/"+galleryarray[curimg])
curimg=(curimg<galleryarray.length-1)? curimg+1 : 0
}
window.onload=function(){
setInterval("rotateimages()", 2500)
}
</script>
<div style="width: 170px; height: 160px">
<img id="slideshow" src="pics/bear.gif" />
</div>
Example:
And there you have it! You can add or delete images to the "pics"
directory, and the slideshow will automatically adapt accordingly. Nifty eh?
|