Search code examples
javascripthtmlimageslider

Javascript simple image slider


I would like to have a simple picture slider. That slider should be in the header of the website and should switch between a small delay. I want it simple and named the pictures 1.jpg, 2.jpg and so on and they are in the folder "bilder".

I have tried a bit and here is my result:

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script type="text/javascript">

    function picture_slider(){
        setInterval( switch_picture(), 3000 );
        return false;
    }

    function switch_picture() {
        for ( var i = 1; i < 7 ; i++ ) {     
            var pfad = "bilder/" + i + ".jpg";
            document.getElementById("bild").src = pfad; 

            i++;
        };
        return false;
    }
</script>
</head>
<body onload="picture_slider();">
    <img id="bild" src="" />
</body>
</html>

I guess, that I did something wrong, because my browser is showing only one picture and is not switching.


Solution

  • jsBin demo

    On every loop you're iterating (for loop) over all your images, resulting in the latest one. Also use only switch_picture (instead of switch_picture()).

    P.S: create an 0.jpg image for this counter:

    function picture_slider(){
        setInterval( switch_picture, 2000 ); // corrected removing "()"
    }
    
    var bild = document.getElementById("bild")
    var i = 0; // Start from image 0.jpg
    
    function switch_picture() { // don't iterate a loop in here!
      bild.src = "bilder/"+ (i++ % 7) +".jpg";
    }