Friday 8 August 2008

Javascript Simple Image Slideshow

This is a simple web page using HTML and Javascript. It displays an image with Next and Previous buttons.

When one of the buttons is pressed, the image is switched with the next or previous image.

As this is a simple example, the filenames for the images are expected to be the same but with incremental numbering. EG. image0.jpg, image1.jpg ... imageN.jpg.

<html>

<head>

<script type="text/javascript">
var img = 0; // Current image

function switchImage(i,d)
{
const imgs = 5; // Total number of images
img+=d;
if(img>=imgs){img=0;}
else if(img<0){img=imgs-1}
i.src = "image"+img+".jpg";
}
</script>

</head>

<body>

<h1>Switch Image Source</h1>

<input type="button" value="Prev" onClick="switchImage(document.getElementById('myImg'),-1);"/>
<input type="button" value="Next" onClick="switchImage(document.getElementById('myImg'),1);"/>
<br/><br/>
<img id="myImg" src="image0.jpg"/>

</body>

</html>

Change the imgs constant value to the total number of images you have in you slideshow.

Done.

See also: Progressed version preloading images and using any filename

No comments: