fading image at random

411 views Asked by At

I wonder if anyone can help or point me in the right direction.

I have a grid of images. What I'm hoping to do is grab all the images on the page and put them in an array(done). Then every 3 seconds I want to to randomly choose an image, fade it out and fade in another image from the same page.

can someone help me with this?

1

There are 1 answers

3
Duckdoom5 On BEST ANSWER

I've got a nice script I made once, it does use jquery though:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
var curIndex = 0;
var src = ['imgs/derp.jpg', 'imgs/derp2.png'];
var fadeTimeInMilliseconds = 2000;
var waitTimeInMilliseconds = 5000;

$(document).ready(function(){
    switchImageAndWait(true);
});

function switchImageAndWait(fadeOut2){
    if(fadeOut2){
        setTimeout(fadeOut, waitTimeInMilliseconds);
    }else{
        var index = Math.floor((Math.random()*src.length))
        if(curIndex == index){
            index++;
            if(index >= src.length){
                index-=2;
            }
        }
        curIndex = index;
        $("#swekker").attr("src", src[index]);
        fadeIn();
    }
}

function fadeOut(){
    $("#swekker").fadeTo( fadeTimeInMilliseconds, 0 , function() { switchImageAndWait(false); });
}

function fadeIn(){
    $("#swekker").fadeTo( fadeTimeInMilliseconds, 1 , function() { switchImageAndWait(true); });
}
</script>

It's a jquery script script that continuously fades in, waits and fades out again.

To use this script simply add it to an image:

<img width="602" height="400" src="imgs/derp.jpg" id="swekker"/>