Creating a JavaScript photo gallery which automatically change

This tutorial explains the manner you can create a JavaScript photo gallery which automatically change.

Prepare 5 images for introducing them in the JavaScript gallery.
Create a HTML file and introduce one of the images selected with the "photo-gallery" id (set the src, width and height attributes corresponding to your own images):

<img src="photos/pic1.jpg" id="photo-gallery" width="420" height="260">

Now let's create a JavaScript function that will automatically unroll the images at one second interval.

Put this code in the head section of your HTML document:


<script type="text/javascript">
var c=0
var s
function photoGallery()
{
if (c%5==0){

document.getElementById('photo-gallery').src = "photos/pic1.jpg";
}
if (c%5==1){

document.getElementById('photo-gallery').src = "photos/pic2.jpg";
}
if (c%5==2){

document.getElementById('photo-gallery').src = "photos/pic3.jpg";
}
if (c%5==3){
document.getElementById('photo-gallery').src = "photos/pic4.jpg";
}
if (c%5==4){
document.getElementById('photo-gallery').src = "photos/pic5.jpg";
}
c=c+1
s=setTimeout("photoGallery()",1000)
}
</script>



We use here the c (initially having 0 value) variable which is incremented every one second. We use the getElementById method (which returns the object with the "photo-gallery" id ) of the document object (that represents the entire HTML page).

Depending of the division remainder ( JavaScript modulus operator: c%5) it is chosen the picture to be displayed.

In the last line of the script it is used the setTimeout() method for calling the photoGallery() function each 1000 miliseconds (that means 1 second).
Now just use the onLoad Event Handler and call the photoGallery() function from the body.
<body onLoad="photoGallery()">
You can also launch application with JavaScrip .


View more tutorials