Saturday, February 26, 2011

Javascript multiple image fadein

I just got multiple images to fade-in on page load using javascript. I thought, i 'll put down how to do it, since all online helps were bit confusing, at the least.

at first, there's an onLoad event handler for img tag. All tutorials just teach you body tags onLoad event handler.

Then, since we are handling multiple images, you have to pass in the image reference to repeat calls of function to change the alpha of the image. here
setTimeout("function_to_change_alpha("+img+")",interval); 
doesnt work. (for reasons beyond my comprehension about javascript quirks.)
the rightway to do it is, by using closure:
setTimeout(function() {function_to_change_alpha(img);}, interval);

For unknown reasons, i couldn't read the opacity property of the object (image) thus passed.
mOpacity = obj.style.opacity; didn't work.
I had to pass in the current opacity value also, to the function and increment it in the function.

Thus, the final version of the function was:

fadeimage = function (obj, opc) {
 if (opc==undefined) opc=0;
 opc += 0.1;
 obj.style.opacity = opc ;
 if (opc<1){
  setTimeout(function() {fadeimage(obj,opc);},300);
 }
}

I used a php script to dynamically load images in a directory, and assign it's filenames as captions to the images, and assign the above fade-in function to images' onload event.

if (!$dir=opendir("photos")) echo "could not open dir" ;
while ( ($file = readdir($dir)) != false ) {
  if (preg_match ("/.jpg$/i",$file)) {
    $name = $file;
    $name = preg_replace("/.jpg/","",$name);
    $name = preg_replace('/\b(\w)/e', 'strtoupper("$1")', $name);
    
    if ($row ==0) echo "<tr>";
    echo '<td> <img src="photos/'.$file.'" class="fadinimage" onLoad="fadeimage(this);"><br><center>'.$name.'</center></td>';
    $row ++;
    if ($row==2 ) {
      echo "</tr>";
      $row =0;
    }
  }
}

and finally set the alpha of the .fadeimage class to 0 in the css file.

here's the final site:


http://midtownpayyanur.orgfree.com/photos.php

1 comment: