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. 

<?php
if (!$dir=opendir("activities")) echo "could not open dir" ;
$javastr = "<script language=\"javascript\">";
$javastr .= "var d = new Array();";
$num=0;
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\"; ";
    $num++;
  }
}
$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>
</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.images.slide.src=d[num].src;
 document.getElementById("slide_caption").innerHTML = d[num].name;
 function slideit() {
  var alfa = 0;
  num++;
  if (num==d.length) num=0;
  setalpha(num,alfa);
  setTimeout("slideit()",2500);
 }
 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.images.slide.src=d[numm].src;
    document.getElementById("slide_caption").innerHTML = d[numm].name;
   }
   alpha += 0.1;
   setTimeout(function() {setalpha(numm,alpha);},50);
 }
 slideit();
</script>

the sample site:
http://midtownpayyanur.orgfree.com/activities.php

2 comments:

  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...

    ReplyDelete