Search code examples
javascriptjqueryhtmlsliderfadein

jQuery: randomize fading divs (regardless number of items)


I have this snippet which makes my divs "slide" every 3 seconds:

$(function(){
    $('.fadein p:gt(0)').hide();
    setInterval(function(){$('.fadein > :first-child').fadeOut().next('p').fadeIn().end().appendTo('.fadein');}, 3000);
});

<div class="fadein">
    <p><img src="">image1</p>
    <p><img src="">image2</p>
    <p><img src="">image3</p>
</div>

I'd like to randomize the order of divs shown.. the problem is that the number of divs isn't going to be the same every time.. so I can't use

setInterval(function() {
  var number = 1 + Math.floor(Math.random() * 3);
  ...

As it's not always going to be 3.. and I can't change the script every time. Can you help me?

Here's a fiddle: http://jsfiddle.net/S4SmM/4/


Solution

  • Use the jQuery Length property. It'll get the amount divs you have and you can use the Math.random function like you want to.

    Edit

    I've edited your fiddle to make it do what I think you want. There's a little problem with it sometimes showing the same picture a few times in a row but I'll let you decide how you want to handle it.

    Here's the code as well

    $(function () {
    $('.fadein p:gt(0)').hide();
    setInterval(function () {
        var randomize = 1 + Math.floor(Math.random() * $('.fadein > p').length);
        $('.fadein > p').fadeOut();
        $('.fadein > :nth-child(' + randomize + ')').fadeIn();
    }, 3000);
    });