1

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.

L84
  • 45,514
  • 58
  • 177
  • 257

3 Answers3

3

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.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

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.

box86rowh
  • 3,415
  • 2
  • 26
  • 37
  • That's not quite what the OP wants. They already have 50 showing at random, what they need to do is rearrange them on the page. – Matt Burland Mar 05 '14 at 01:41
  • ok, added code to not only show the random question, but also add it to the end of the display list, hence re-ordering it. – box86rowh Mar 05 '14 at 01:46
0

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();
Raz Wilson
  • 64
  • 4