Ian Jamieson
Ian Jamieson

Reputation: 4816

jQuery random image fader

I have a header area which is divided up into block areas for images, these images are absolutely positioned within the block and are all different heights and widths.

I have a URL /random-image?width=x&height=y&random=34234 which generates a random image to use for the specific place.

I want these images to randomly fade out and change for another random image, or to fade on click. I have got it working, except the "setTimeout" or "setInterval" only triggers once. I need it to be on an infinite loop.

Here is my code, any ideas:

jQuery(document).ready(function ($) {

$('#main-image img').live('click', function() {     
    var $image = $(this),
    width = $image.width(),
    height = $image.height(),
    random = Math.random();        

    $('<img src="/random-image?width='+width+'&height='+height+'&random='+random+'" />').hide().load(function() {
        $(this)
        .appendTo($image.parentsUntil('div.columns'))
        .fadeIn('slow', function() {
            $image.remove();
        });

    });        
});

$('#main-image img').each(function() {
    var $image = $(this),
    randVal = Math.round(5000 + Math.random()*(30000 - 5000)) ;

    setTimeout(function() {
        console.log($image.attr('src'));
        $image.trigger('click');
    },randVal);
});

});

Upvotes: 0

Views: 397

Answers (1)

Scott Sauyet
Scott Sauyet

Reputation: 50787

You need to call your setTimeout function again at the end of the fade. The easiest way I can think to do that is to name the function you're using and then call it from two places, as in the following (entirely untested) version:

jQuery(document).ready(function ($) {

var changeImage = function() {
    var $image = $(this),
    randVal = Math.round(5000 + Math.random()*(30000 - 5000)) ;

    setTimeout(function() {
        console.log($image.attr('src'));
        $image.trigger('click');
    },randVal);
};

$('#main-image img').live('click', function() {     
    var $image = $(this),
    width = $image.width(),
    height = $image.height(),
    random = Math.random();        

    $('<img src="/random-image?width='+width+'&height='+height+'&random='+random+'" />').hide().load(function() {
        var newImage = this;
        $(this)
        .appendTo($image.parentsUntil('div.columns'))
        .fadeIn('slow', function() {
            $image.remove();
            changeImage.call(newImage);
        });

    });        
});

$('#main-image img').each(changeImage);

});

Upvotes: 1

Related Questions