L84
L84

Reputation: 46308

Random Ordered Divs

I have a quiz that has 100+ questions. When the questions load, only 50 of the questions show. The rest are hidden. I am using the following code:

CSS

.question{
   display:none;
}

HTML

<div class="question">
    <!-- Code for Each Question -->
</div>

<!-- Repeat 'question div' for every question. -->

JS

var divs = $("div.question").get().sort(function(){ 
   return Math.round(Math.random())-0.5;
}).slice(0,50)
$(divs).show();

The above code works great, however, instead of just showing 50 questions I would like to show 50 questions in a random order. How would I modify my code to not only show only 50 questions but show them in a random order?

I should note that the above JS was used from another question. I don't fully understand Math.random() and unsure how to randomly display the 50 divs that it does show.

Note: Solution must be pure client side code.

Upvotes: 1

Views: 136

Answers (3)

Raz Wilson
Raz Wilson

Reputation: 64

It sounds like you actually want to move the elements around on the page.

Assuming the questions are within a container div, something like this might do the trick:

var $divs = $("div.question").sort(function(){ 
   return Math.round(Math.random())-0.5;
}).slice(0,4)

// remove them
$divs.detach();

// reposition them
$('#questionContainer').append($divs);

// show
$divs.show();

Upvotes: 0

Bergi
Bergi

Reputation: 664538

To re-order the divs on the page, you will need to re-append them in the shuffled order. What you're currently doing is getting the elements, selecting 50 of them and showing those (in random sequence, but not changing their position in the dom).

Instead of $(divs).show(); use

$(divs).appendTo(questionContainer).show();

Also notice that you shouldn't use sort() to shuffle an array.

Upvotes: 3

box86rowh
box86rowh

Reputation: 3415

first, create an array containing 0-99 (if you have 100 questions)

var arr = new Array();
for(var i=0; i < 100; i++){
arr[i] = i;
}

then shuffle the array

var shuffle = function(o){ //v1.0
    for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
};
var shuffled = shuffle(arr);

then loop through the shuffled array showing the first 50.

    for(var i = 0; i < 50; i++){
var thisOne = $($("div.question")[shuffled[i]]);
thisOne.parent().append(thisOne); 
    thisOne.show();
    }

I cannot guarantee this will copy paste in and work, but it should get you started.

Upvotes: 0

Related Questions