1

I want to replace the contents of a div with the values found in an array. I want to keep each value within the div for 3 seconds each. Here's my code so far:

        var images = ['a.jpg', 'b.jpg', 'c.jpg'];

        for (i = 0; i < images.length; i++) {
          $('#slideShow').html("<img src='../"+images[i]+"' alt='' />");
        }

This of course changes the images so fast that the human eye only sees one image being in the div at all times. I want to keep each image for 3 seconds before the next .html() is done on the div. How to do this?

1
  • what JCOC611 said, you should consider changing the src attribute of am IMG element rather than injecting new one into the DOM each time Commented Feb 12, 2011 at 2:16

2 Answers 2

3

Try this:

images = ["a.jpg", "b.jpg", "c.jpg"];

function change(i){
   if(!images[i]){return false}
   else{
     $("#slideShow").src=images[i];
     setTimeout( function(){ change(i+1) }, 3000);
   }
}
change(0);

Haven't tested it but it should work.

Sign up to request clarification or add additional context in comments.

2 Comments

should wrap the variable i after array length
Your reference to the arguments object will be that of the function passed to the setTimeout instead of that of the change function. Why not just do change(i+1)?
1

This answer assumes that you want to loop. If not, comment and I'll rewrite.

<script>
var images = ['a.jpg', 'b.jpg', 'c.jpg'];
var curimage = 0;
function changeImage() {
    $('#slideShow').html("<img src='../"+images[curimage]+"' alt='' />");
    curimage++;
    if (curimage > images.length) curimage = 0;
}
changeImage();
window.setInterval(changeImage, 3000);
</script>

I have tested this answer.

3 Comments

A little shorter/cleaner way of resetting curimage to 0 would be to use the modulus operator: curimage = ++curimage % images.length
@patrick dw: +1 Great point; I like your way better; however, it may be harder for the inexperienced to understand, so for now I'll leave as is....
Understood. That's always an important consideration.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.