PDA

View Full Version : Rotating Image Script


w1sh
05-21-2009, 08:34 PM
This is my first time really studying JavaScript and I know this is common all over the internet, but I made this from scratch.

Anyway, I'm fairly new here and don't want to become one of those "tell me how to do this" kinda guys. I'd rather help and be helped. So here's the script.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>JavaScript Playground</title>
<style>
body {
font-family:Verdana, Geneva, Arial, Helvetica, sans-serif;
font-size:12px;
width:600px;
margin:auto;
}
#rotator {
position:relative;
left:100px;
top:110px;
}
</style>
</head>
<body>
<h1>Custom Image Rotator</h1>
<script type="text/javascript">
<!--
// Name these files after your image names. And add more as needed.
// Feel free to change the extension.
var y=new Array();
y[0]="moon.jpg";
y[1]="saturn.jpg";
y[2]="sun.jpg";
// y[3]="image_name.jpg";

// This is your random number calculator. Change 2 to 1 less than the number of images
// (JavaScript counts 0 as 1 for some reason).
var x=Math.round(Math.random() * 2);

// This puts that random number (x) into your array (y ).
var z=y[x];

// This just shows you what all numbers are being played with. Feel free to DELETE this.
document.write("X = ",x);
document.write("<br />");
document.write("Y = ",y);
document.write("<br />");
document.write("Z = ",z);
document.write("<p>&nbsp;</p>");
// Below is the actual code to get this working. "img" is your directory so change it.
// document.write("<img src=\"img/",z,"\" />");
//-->
</script>

<h2>Playing with Divs</h2>
<div id="rotator">
<script type="text/javascript">
document.write("<img src=\"img/",z,"\" />");
</script>
</div>
</body>
</html>


This script assumes you have 3 images (moon.jpg, saturn.jpg, and sun.jpg) located in a folder in the same directory called img (which can be modified in the script within #rotator).

Hope someone can make use of this. :thumbsup: