Search code examples
javascriptjqueryrotatortestimonials

Adding randomization to simple testimonial rotator


There was an awesome, super-minimal testimonial rotator that I found here, but I'm curious as to how I might get it to simply randomize the results. Here's the rotator as it now functions:

$('.testimonials div:first').show();

setInterval(function(){ 
    $('.testimonials div:first-child')
        .fadeOut(1000)
        .next('div')
        .delay(1000)
        .fadeIn(1000)
        .end()
        .appendTo('.testimonials') 
},3000);

http://jsfiddle.net/xXRwA/9/


Solution

  • Try this:

    var $items = $('.testimonials .item');
    
    function getRandomItem(){
        return $items.eq(Math.floor($items.length * Math.random()));
    }
    
    getRandomItem().show();
    
    setInterval(function(){ 
        var $outgoing = $items.filter(':visible');
        var $incoming = getRandomItem();
        $outgoing.fadeOut(1000, function(){
            $incoming.fadeIn(1000);
        });
    }, 3000);
    

    Demo: http://jsfiddle.net/JWGbz/6/