|
If you followed and completed the Basic Slide Show tutorial you might be wondering how to make it more dynamic so all you have to do is add the images to a directory and they will be displayed. Using PHP in combination with JavaScript it is quiet simple
Effectively the plan is this. We create a external PHP file that will pose as a JavaScript file to the HTML document. This PHP file will dynamically create the array of images needed to run through.
Make sense? Well lets get cracking. Let us start with the PHP page first. We will call this one slideShow.php
ob_start(); //Output buffering
//first we send the header to the browser to process the page
//as JavaScript
header("content-type: application/x-javascript");
$imgDir = "images/"; // the directory the iimages reside in
$counter = 0; // our file counter;
$list = "";
//regex pattern to check file extensions
$pattern="(.jpg$)|(.gif$)";
//read through the dir and create the img list
if($dir = opendir($imgDir)) {
while(false !== ($file = readdir($dir))){
if(eregi($pattern, $file)){
$path = $imgDir . $file;
$list .= 'images['.$counter.']="'.$path .'";' .chr(13);
$counter++;
}
}
closedir($dir);
}
//echo the array declaration
echo "var images = new Array()" . chr(13);
echo $list;
ob_end_flush();
Now save the file as slideShow.php in the directory above the images directory.
Next we create the HTML file. Very simple, I am not going to explain it as we did this in the Basic Slide Show tutorial. Below is the page
<!DOCTYPE HTML
PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1">
<title>Image List</title>
<!-- add reference to external file -->
<script language="JavaScript"
type="text/javascript" src="slideShow.php"></script>
<script language="JavaScript"
type="text/javascript">
var counter = 0;
var showImageFor = 3; //seconds
function showImage(){
if(counter == images.length){
counter = 0;
}
document.images.imageCotainer.src = images[counter];
counter++;
}
function runImages(){
milliseconds = showImageFor * 1000;
setInterval("showImage()", milliseconds);
}
</script>
</head>
<body onload="runImages()">
<img src="images/image0.jpg"
name="imageCotainer" id="imageContainer" >
</body>
</html>
The only change we have made to the file is the addition of the script tag containing the path to the external file, which is the PHP file posing as a JavaScript file.
|