Why this slide images don't run? It is very strange

35 views Asked by At

I view only the first image. I checked every word but I don't find the error. This is the code:

www.jsfiddle.net/4kgg5teg/

Thank you, and sorry for bad english.

3

There are 3 answers

1
pzp On

I went ahead and simplified your code considerably. There were numerous problems with it, such as your nesting and passing a string to setTimeout.

HTML

<body>
    <div id="mainbox">
        <img src="list/1.jpg" id="slide" height="605px" width="800px" />
    </div>
</body>

The only change there was making the name attribute into an id. This is a choice of preference; I think it makes the code more readable and reliable. (Instead of document.images.slide we can now do document.getElementById("slide") in our JavaScript code.

JavaScript

var slide, step;

slide = document.getElementById("slide"); 
step = 0;

setInterval(function () {
    slide.src = "list/" + (step+1) + ".jpg";
    step++;
    step %= 7;
}, 2500);

As you can see, my code is considerably shorter. The two main changes I made was cutting out the img array (which was plain confusing) and using setInterval instead of setTimeout to avoid recursion. Additionally I fixed the references to your images to list/[img #].jpg from img[img #].src (I got that path from your HTML). Another minor change I made was using the remainder operator (%) (also known as modulo operator) instead of the if/else to make step "wraparound."

I hope that my revisions solved your problem and more importantly helped you realize how to solve issues like this one in the future.

Best of luck,
pzp

1
j__ On

Here you go

http://jsfiddle.net/4kgg5teg/1/

It was the setTimeout you need to pass in the function, not a string of the name. Also the function was nested in the for loop which it didn't need to be.

0
dajnz On

In your jsfiddle on line 13

 setTimeout("slideit()", 2500);

change string "slideit()" to just slideit, like this:

 setTimeout(slideit, 2500);

You have to specify a function for setTimeout, not a string with a name of the function, like you did