user784576
user784576

Reputation: 15

Javascript automatic next image

I created this site which uses a simple javascript function to show images based on the user mousing over or clicking numbered boxes on the right. Now after testing it's been determined that an automatic slideshow should be added on top of this, so that next image will show after a few seconds.

http://www.philippedollo.com/photo/fineart/f_amw.htm

Is there a way to amend this code easily to make it happen easily? --

function showPic(whichpic) {
    if (document.getElementById) {
        document.getElementById('placeholder').src = whichpic.href;
        if (whichpic.title) {
            document.getElementById('desc').childNodes[0].nodeValue = whichpic.title;
        } else {
            document.getElementById('desc').childNodes[0].nodeValue = whichpic.childNodes[0].nodeValue;
        }
        return false;
    } else {
        return true;
    }
}

Upvotes: 1

Views: 464

Answers (2)

Loktar
Loktar

Reputation: 35319

The following should work for you, I tested it and it works fine on my end.

var curPic,
    gallery,
    pics;

function cyclePic(){
    if(curPic < pics.length){
        showPic(pics[curPic]);
    }
    curPic++;
    setTimeout(cyclePic,5000);
}

function showPic (whichpic) {
     if (document.getElementById) {
      document.getElementById('placeholder').src = whichpic.href;
      if (whichpic.title) {
       document.getElementById('desc').childNodes[0].nodeValue = whichpic.title;
      } else {
       document.getElementById('desc').childNodes[0].nodeValue = whichpic.childNodes[0].nodeValue;
      }
      return false;
     } else {
      return true;
     }
}

window.onload = function(){
    curPic = 0,
    gallery = document.getElementById("gallery"),
    pics = gallery.getElementsByTagName("a");
    cyclePic();
}

Upvotes: 0

Matt Ball
Matt Ball

Reputation: 360046

Use setInterval().

function getNextPic()
{
    // ???
}

setInterval(function ()
{
    showPic(getNextPic());
}, 3000); // 3 seconds

There's no need for the if(document.getElementById) check, since the function is 100% cross-browser.

function showPic(whichpic)
{
    document.getElementById('placeholder').src = whichpic.href;

    document.getElementById('desc').childNodes[0].nodeValue = whichpic.title ?
        whichpic.title : whichpic.childNodes[0].nodeValue;

    return false;
}

Upvotes: 1

Related Questions