Home | Web Design | App / Game development | Flash | Flash Games | Graphic Illustration | Technical Illustration | Contact | Site Map    Twitter
 
  Galaxy Graphics Limited

Technical InformationJavascript Knowledgebase: Randomising DOM elements

In the HTML before the script

<div id="myDiv0">a</div>
<div id="myDiv1">b</div>
<div id="myDiv2">c</div>
<div id="myDiv3">d</div>
<div id="myDiv4">e</div>

In the HTML after the divs

<script>

function randomInt (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}

Array.prototype.xshuffle = function(unsort) {
// Unsort is the number of items you don't want shuffled, starting from the beginning
var len = (this.length)-1;
var i = len;
while (i>unsort) {
var p = randomInt(unsort,len);
var t = this[i]; // Assign data at original location i to var t
this[i] = this[p]; // Assign original location i the data of random location p
this[p] = t; // Assign original locaton i's data to random location p
// Effectivly, We've chosen an array location at random and swapped it's content
// with that of the content at location i
i --;
}
};

itemArray = new Array();
itemArray[0] = "Hello";
itemArray[1] = "there";
itemArray[2] = "World";
itemArray[3] = "it works";
itemArray[4] = "today";

//shuffle(itemArray);
itemArray.xshuffle(1);

for (var i=0;i<itemArray.length;i++){
var divid = "myDiv"+i;
var actual_div = document.getElementById(divid);
// If the div exists in the DOM AND something exists in the array
if (actual_div != null && itemArray[i]){
//document.write("actual_div = " + actual_div + "divid = " + divid + "<br>");
actual_div.innerHTML = itemArray[i];
} else {
// Else remove that DIV from the page
actual_div.parentNode.removeChild(actual_div);
}
}

</script>

 
Site content Copyright © 2001-2014 Galaxy Graphics Limited. | Privacy Policy | Terms of use