▼  Site Navigation Main Articles Search  ▼  Anime + Manga Anime Reviews Anime Characters Gallery Screenshots Manga Reviews  ▼  Misc News Links to Webcomics Bible Quotes About Older Musings
site version 7.3
Javascript –– randomly cycle through images
written by: admin

Date Written: 11/28/09 Last Updated: 1/15/10

I got a lot of help with this script from the kind people at www.dynamicdrive.com/forums

This script will cycle through images at the click of a button without refreshing the page.  I really only have one use for it on my site and that is for the memoblog page.  When I create a new memo a random image is generated, but I almost want a different image, so I would refresh the page till I got an image I was happy with.  With this script I won't have to worry about losing the other information I have typed in.

Below is a working example:

$imgdir = 'images/screenshots';
$allowed_types = array('png','jpg','peg','gif','bmp');
$dimg = opendir($imgdir);
while($imgfile = readdir($dimg))
<img id="img" src="" style="width:135px; height:135px;" alt="">
<br><br><button onclick="newi();return false;">different image</button>
<form name="myform">
<div><input type="text" name="outputtext"></div>
<script type="text/javascript">
function newi(){++newi.Num;
if(newi.Num > newi.ar.length - 1){
newi.Num = 0;
newi.img.src = 'images/screenshots/' + newi.ar[newi.Num];
newi.img.src = 'images/screenshots/' + newi.ar[newi.Num];
newi.output.value = newi.ar[newi.Num];
newi.Num = 0;
newi.ar = new Array(<?php echo "$Statss"; ?>);
newi.img = document.getElementById('img');
newi.output = document.forms.myform.elements.outputtext;

It has been tweaked slightly to center it and the images were not randomized.

multiple buttons
In this example you have greater control over the cycling of images with a forward, back, and original image buttons.

<div style="padding-right:15px;"><img id="imgo" src="" style="width:135px; height:135px;" class='floatimgleft' alt=""><button onclick="return newio(-1);return false;">prev</button>
<button onclick="return newio();return false;">original image</button>
<button onclick="return newio(1);return false;">next</button></div>
<form name="myformo"><input type="text" name="outp">

<script type="text/javascript">
function newio(n){
newio.Num += n || -newio.Num;
newio.Num = newio.Num < 0? newio.count - 1 : newio.Num % newio.count;
newio.imgo.src = '/images/screenshots/' + newio.ar[newio.Num];
newio.output.value = newio.ar[newio.Num];
return false;

newio.Num = 0;
newio.ar = new Array('gunslingergirl30.jpg', 'gunslingergirl34.jpg', 'gits25.jpg', 'gunslingergirl5.jpg', 'iria4.jpg', 'noir113.jpg', 'noir17.jpg', 'gunslingergirl3.jpg', 'elfenlied4.jpg','elfenlied2.jpg', 'dragonhalf12.jpg', 'blood2.jpg', 'cowboybebop32.JPG', 'battleangel1.jpg');
newio.count = newio.ar.length;
newio.imgo = document.getElementById('imgo');
newio.output = document.forms.myformo.elements.outp;

TAGS: javascript, images

Go to phpbb thread.
copyright 2005–2021