1

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

$(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);
});

Here's the fiddle. The problem is that sometimes the slides are the same (as the random number generated is the same twice in a row). Can you help me creating some variable to store the last number generated so when the function calls Math.random(), if that number equals the last number generated it calls it again.

2 Answers 2

2

You should check which p are visible before doing you random. Then, you should play within that stack to be sure you are not randoming the same image twice. This code does it :

$(function () {
    $('.fadein p:gt(0)').hide();
    setInterval(function () {
        var $p = $('.fadein > p').not(':visible') //Select only the hidden one
        var randomize = Math.floor(Math.random() * $p.length); //Use only those hidden, remove the 1 since we are now on a 0-based index
        $('.fadein > p').fadeOut();
        $p.eq(randomize).fadeIn(); //Use eq on the hidden p
    }, 3000);
});

http://jsfiddle.net/775pR/3/

Sign up to request clarification or add additional context in comments.

2 Comments

Wow! Perfect! Just as last touch... how can I make also the first p random? I tried setting p:gt(-1) but doesn't quite work..
@DioCane with a single selector, you can't. But you can use that : jsfiddle.net/775pR/9
1

Try with this example if you want to use "all in one" selector:

$('.fadein > p' ).fadeOut();
$('.fadein > p:not(:visible):eq(' + Math.floor( Math.random() * ($('.fadein > p' ).length-1) ) + ')' ).fadeIn();

FIDDLE

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.