Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I cycle through a set of images?

Tags:

javascript

I'm trying to make a banner that cycles through 3 images using JavaScript.
Each image should be displayed for 10 seconds before changing.

I wrote some code but it is not working. It stays stuck on the first image. The Image does not change as I want it to.

Can you see anything in the code and point out my mistakes?

Code as follows:

<script type="text/javascript">
    function changeBanner(){
        var img = new array

        img[0] = document.images[0].src
        img[1] = document.images[1].src
        img[2] = document.images[2].src

        var currentimg = img[0]

        if(currentimg == img[0]) {
            currentimg = img[1]
        }

        if(currentimg == img[1]) {
            currentimg = img[2]
        }
    }
</script>

HTML as follows:

<body onload="var start=setInterval('changeBanner()', 10000;">
    <div id="wrapper">
        <div>
            <img src="budda.JPG" width="900px" height="300px" />
        </div>
...
like image 208
Timothy Coetzee Avatar asked Mar 25 '23 08:03

Timothy Coetzee


1 Answers

var index = 0;

function changeBanner() {
    [].forEach.call(document.images, function(v, i) {
        document.images[i].hidden = i !== index
    });
    index = (index + 1) % document.images.length;
}
window.onload = function() {
    setInterval(changeBanner, 1000)
};

http://jsbin.com/emilef/2/edit

like image 98
user2153497 Avatar answered Mar 31 '23 20:03

user2153497