4

I am completely new to coding, so please bear with me if my questions are stupid (& please write any answer out as code as I will not get it otherwise...). I am working on a Qualtrics survey page where I have two optional answers - each answer is a list of items. I am trying to shuffle the lists so that each participant view them in a different order. I got these codes below from the web.

My HTML lists look like this:

<div id="enriched">
    <div class="list_item">lots of sunshine</div>
    <div class="list_item">gorgeous beaches and coral reefs</div>
    <div class="list_item">ultra-modern hotel</div>
    <div class="list_item">very cold water</div>
    <div class="list_item">very strong winds</div>
    <div class="list_item">no nightlife</div>
</div>

Whereas my javascript code is this:

var list = document.getElementById("enriched");
function shuffleNodes() {
    var nodes = list.children, i = 0;
    nodes = Array.prototype.sort.call(nodes);
    while(i < nodes.length) {
       list.appendChild(nodes[i]);
       ++i;
    }
}
shuffleNodes();

However, it only shuffles the list once from the original version. After that every next participant just see that version with no further shuffling happening. After which I need to somehow make it work for both lists too.. I'm a little stressed.

I also tried an array code, but I couldn't make it work.

Danield
  • 121,619
  • 37
  • 226
  • 255
  • 3
    You're not shuffling nodes anywhere in your code - you're sorting them to place in some specific order. Sorting them again and again just places them in same order, so you don't see any changes after the first sort. – Oleg V. Volkov Dec 16 '15 at 11:45
  • http://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array – shareef Dec 16 '15 at 11:54

2 Answers2

0

As the function name suggests, the line nodes = Array.prototype.sort.call(nodes); doesn't shuffle the contents - it sorts it. So you're getting a consistent ordering each time.

You may want to see How to randomize (shuffle) a JavaScript array? for a shuffling implementation.

Community
  • 1
  • 1
Prisoner
  • 49,922
  • 7
  • 53
  • 105
0

This should create a new random_list array:

var random_list = [];

for ( i = 0; i < nodes.length; i ++ ) {
  random_list.push( nodes[i].innerHTML );
}

random_list.sort( function() {
  return Math.random() - 0.5;
});
andreasonny83
  • 1,213
  • 11
  • 19