0

I'm trying to randomize an array of div classes and then fade in different divs (facts) each time a button is clicked. However, what I can't work is how to display a completely different div each time, so that a div is not repeated on click.

My current code is:

$(document).ready(function () {

    var facts = Array('.fact1', '.fact2');

    $(document).delegate('a.eggbutton', 'click', function () {

        $(fact).fadeOut('slow');

        var fact = facts[Math.floor(Math.random() * facts.length)];

        $(fact).fadeIn('slow');

    });

});
5
  • What's your current HTML? Commented Jun 12, 2013 at 12:04
  • What's wrong with this approach? Commented Jun 12, 2013 at 12:06
  • Is your problem that exist the possibility of showing the same div 2 or more times in a row with this approach? Commented Jun 12, 2013 at 12:08
  • Yes exactly @ClaudioRedi Commented Jun 12, 2013 at 12:10
  • Looks like $(fact).fadeOut('slow'); here fact always undefined, no?! Commented Jun 12, 2013 at 12:10

4 Answers 4

3

hope this helps: http://jsfiddle.net/AMmwL/6/

code

function randomFact(){
    var factsArr = $(".fact");
    $(".fact").hide("slow");
    var rnd = Math.floor((Math.random()*(factsArr.length-1)));
    $(factsArr[rnd]).show("slow");
}
Sign up to request clarification or add additional context in comments.

8 Comments

+1 for different approach but you can directly show the item with index why do you need the id. $(factsArr[rnd]).show() should work or factsArr.find() with index selector.
@BeNdErR -1 +1 = 0. What's the point of those trailing operations?
That is a problem. If random() returns 1, then rnd will be out of the array's bounds.
This should solve it: var rnd = Math.floor(Math.random()*(factsArr.length-1));
this is a nice bit of code but it still doesn't prevent items from repeating on click
|
2

I think your problem is when you show a div you are not hiding it when showing the other one. You did try doing it by $(fact).fadeOut('slow'); but as fact is local variable it won t work as you expected.

as a first soluyion you can define it in global scope like window.fact = ''

or also add class when showing to div and next time you are showing another div just hide it like below

$(".visibleDivClass").fadeOut('slow').removeClass("visibleDivClass");
...YOUR CODE...
$(fact).fadeIn('slow').addClass("visibleDivClass");

1 Comment

I write it according to your question but to be honest the approach of bender's is more correct, of course if it fits your situation e.g if you can give all of them same class and different id and you only want to display divs.
1

One way to guarantee that you will not generate the same value twice is to keep a log of the last generated value and generate another one if the same value is generated. Simply:

$(document).ready(function () {

    var facts = Array('.fact1', '.fact2');

    var currentValue = 0;

    $(document).delegate('a.eggbutton', 'click', function () {

        $(fact).fadeOut('slow');

        var newValue = 0;

        while(newValue == lastValue){
            newValue = Math.floor(Math.random() * facts.length);
        }
        currentValue = newValue; 

        var fact = facts[currentValue];

        $(fact).fadeIn('slow');
    });
});

This will guarantee that the same fact is not displayed twice and the uniform random generator will guarantee a mostly uniform distribution.

Comments

0

What about doing something like:

var arrayIndex = 0;

$(document).ready(function() {

    var facts = Array('.fact1','.fact2');

    $(document).delegate('a.eggbutton', 'click', function(){ 

    $(fact).fadeOut('slow');

    arrayIndex++;
    if (arrayIndex % facts.length == 0) shuffle(array);

    var fact = facts[arrayIndex % facts.length];

    $(fact).fadeIn('slow');

});

I assume you can find a suffle method for javascript but one can be found here:

How can I shuffle an array?

A problem with this approach is that you can still get the same "random" number after a shuffle but you can further randomize it by doing (pseudo-code follows):

while (randomNumberForIndexBeforeShuffle == randomNumberForIndexAfterShuffle) {
   arrayIndex++;
   re-calculate randomNumberForIndexAfterShuffle
}

1 Comment

Obviously I scribbled some code quickly and I expect there will be a bug or so. You get the idea though - thats the point. EDIT: Make sure you write a shuffle function

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.