Monday, February 28, 2011

javascript image slideshow

php used to open a directory, select image files in it (even if it contains only images, this check is necessary, otherwise, we'll get '.' and '..' files too. php 'echos' a script which initialises an array of images of these images. the browser just gets the script text from the server, which makes it set the array. 

if (!$dir=opendir("activities")) echo "could not open dir" ;
$javastr = "<script language=\"javascript\">";
$javastr .= "var d = new Array();";
while ( ($file = readdir($dir)) != false )
  if (preg_match ("/.jpg$/i",$file)) {
    $name = preg_replace("/.jpg$/","",$file);
    $javastr .= "d[$num] = new Image();";
    $javastr .= "d[$num].src = 'activities/$file';";
    $javastr .= "d[$num].name = \"$name\"; ";
$javastr .= "</script>";
echo $javastr;

a placeholder 'div' defined.

<div id="para">
<div id="activity_div" >
 <div id="slide_caption" ></div>
 <div id="slider"><img name="slide"   /></div>

In the javascript, a function is iterated to change the slides, passing it the serial number of the slide to be put up. It calls another function which calls itself, till it has finished fading out the current slide, change the image source of the slide, then fading in the slide.   The loop is within the nested function. In javascript, nested function cannot be called within a loop, so, it can't be in the first function.

<script language="javascript" >
 var num=0;
 document.getElementById("slide_caption").innerHTML = d[num].name;
 function slideit() {
  var alfa = 0;
  if (num==d.length) num=0;
 function setalpha(numm, alpha) {
   if (alpha>2) return;
   if (alpha<1) {
     document.getElementById("slider").style.opacity = 0.9-alpha;
   else if (alpha>1.1) {
     document.getElementById("slider").style.opacity = alpha-1;
   else  {
    document.getElementById("slide_caption").innerHTML = d[numm].name;
   alpha += 0.1;
   setTimeout(function() {setalpha(numm,alpha);},50);

the sample site:


  1. Went through your site... I think the tab design can be made a bit more slick, use jQuery tabs or some javascript library for the same... or a simple javascript with some css work would do... Loved the current work but...