Dave's Brain

Browse - programming tips - javascript slideshow

Date: 2007dec21

Q.  How do I make a simple slideshow in javaScript?

A.  You can are running Apache, perl and Firefox on your laptop (as I am) 
save these three files in the folder where the files are.
I have run this on a Windows XP machine.  Please note: this is *not*
intented to be played over the internet but where the
server and client are on the same box.

----  file index.cgi -----------------------------------------------------------
#!/usr/bin/perl

use strict;

sub getImages($)
{
	my($dir) = @_;
	local(*DIR);
	my(@files);
	
	if (!opendir(DIR, $dir)) { return (); }
        @files = grep(!/^(\.|\.\.)$/, readdir(DIR)));
        @files = sort(grep(/\.jpg$/i, @files));
	closedir(DIR);
	return @files;
}

sub main()
{
	my(@files, $file, $is_first);
	
	print "Content-type: text/html\n\n";
	print "<link rel=stylesheet href=player.css type=text/css>\n";
	print "<script>\n";
	print "var gaFile = new Array(\n";
	@files = getImages('.');
	$is_first = 1;
	for $file (@files)
	{
		if (!$is_first) { print ","; }
		$is_first = 0;
		print "\'$file\'";
	}
	
	print ");\n";
	print "</script>\n";
	print "<script src=player.js></script>\n";	
	print "<body onLoad=\"player()\"><center><img id=the_image></center><img id=preload style='display:none'></body>";
}

main();

----  file player.js  ----------------------------------------------------------

var giCurrent = -1;
var gaImg = new Array;

function getDim(file) {
	var img, growth, width, height;
	var win_width, win_height;
	
	win_width = window.innerWidth;
	win_height = window.innerHeight;
	
	img = document.getElementById('preload');
	img.src = file;
	
	width = win_width;
	growth = win_width / img.width;
	height = growth * img.height;

	if (height > win_width) {
		height = win_height;
		growth = win_height / img.height;
		width = growth * img.width;
	}
	
	width = Math.floor(width);
	height = Math.floor(height);
	
	return new Array(width, height);
}

function showNext() {
	var file, dim, width, height, obj;
	
	giCurrent++;
	if (giCurrent == gaFile.length) {
		giCurrent = 0;
	}
	file = gaFile[giCurrent];
	
	dim = getDim(file);
	width = dim[0];
	height = dim[1];

	obj = document.getElementById('the_image');
	obj.src = file;
	obj.style.width = width;
	obj.style.height = height;
	
	setTimeout('showNext()', 5000);
}

function preloadAll() {
	var	i, img;
	
	for (i = 0; i < gaFile.length; i++) {
		img = new Image;
		img.src = gaFile[i];
		gaImg.push(img);
	}
}

function player() {
	preloadAll();
	showNext();
}

----  file player.css  ---------------------------------------------------------

* {
	padding: 0px;
	margin: 0px;
}

body {
	background-color: black;
}

Add a comment

Sign in to add a comment
Copyright © 2008, dave - Code on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License.