Randomize the display order of content on my page.

What I needed to do: Randomize the display order of content on my page.

What I found: As the first step, I started to look around to see if someone had already written a javascript for this.

And I found one really good one on dynamic drive. They have just about everything!
http://www.dynamicdrive.com/dynamicindex17/randomcontentorder.htm

Where I was getting stuck: So while this script was working really well, my div’s (that I needed displayed  in a random order) had buttons
that sent ajax requests and received html response. And those stopped working.

My own alternate solution: Here’s the solution I came up with. It may not be most optimized, but for the little content on my page, it works very well.

The logic:

1. I defined a set of css classes to absolute position my div’s. Each of these classes ended with a number. For. e.g .cls1, .cls2…and so on.
2. I created a javascript function, that randomly picks a number from a pre-defined array of numbers.
3. I use this random number to apply the css classes and randomly place my div’s on the page.

<style>
#mycontainer {position:relative;} // you need to set this position to relative to have the child div’s position in relation to this.
.cls1 {position:absolute; top:0px;} // position absolute to where you want the div’s on the page.
.cls2 {position:absolute; top:20px;}
.cls3 {position:absolute; top:40px;}
.cls4 {position:absolute; top:60px;}
.cls5 {position:absolute; top:80px;}
.cls6 {position:absolute; top:100px;}
</style>

<script type=”text/javascript”>

function randOrd(){return (Math.round(Math.random())-0.5);}

function J$(eleID){ return document.getElementById(eleID);}

//this is where we assign random classes to our div’s
window.onload=function() {
anyArray = new Array(‘1′,’2′,’3′,’4′,’5′,’6’);
anyArray.sort( randOrd );

J$(‘mydiv1’).className = “cls”+anyArray[0];
J$(‘mydiv2’).className = “cls”+anyArray[1];
J$(‘mydiv3’).className = “cls”+anyArray[2];
J$(‘mydiv4’).className = “cls”+anyArray[3];
J$(‘mydiv5’).className = “cls”+anyArray[4];
J$(‘mydiv6’).className = “cls”+anyArray[5];
}

</script>

<div id=”mycontainer”>

<div id=”mydiv1″>DIV 1</div>
<div id=”mydiv2″>DIV 2</div>
<div id=”mydiv3″ >DIV 3</div>
<div id=”mydiv4″ >DIV 4</div>
<div id=”mydiv5″ >DIV 5</div>
<div id=”mydiv6″ >DIV 6</div>

</div>

FINAL RESULT: Click here to download the html file.

Leave a comment