Categories:

Randomizing the display order of content using JavaScript

HTML demands that content be displayed either sequentially, or at least in some static order inside the webpage. Using JavaScript, we can jiggle things up, and display pieces of content that randomly interchange order. The result is a group of content that randomly changes display position each time the page is loaded, allowing each of them to receive equal attention from viewers.

In the above, three lines of content are displayed in random order. Reloading the page will yield a new, different ordering.

So how are the content rotated? Well, first off, in order for JavaScript to do any kind of manipulation on textual content, they have to be stored inside variables. An array will do nicely:

var contents=new Array()
contents[0]='<img border="0" src="m1.gif">Netscape developed JavaScript in 1996'
contents[1]='<img border="0" src="m2.gif">JavaScript is not Java'
contents[2]='<img border="0" src="m3.gif">You can cut and paste JavaScript'

To the heart of the matter now- randomizing the order of the array elements before writing them out (displaying them). A kind of "trial and error" technique is employed here. We continuously generate a random number between 0 and array length-1, and test each time whether the element at that index has been written out. If not, write it out, "mark it", and move on, until all non marked elements (which initially every array element is) have been written out. By the end of the process, all the content would have been displayed, and in a random order.

var i=0
//variable used to contain controlled random number 
var random
var spacing="<br>"
//while all of array elements haven't been cycled thru
while (i<contents.length){
	//generate random num between 0 and arraylength-1
	random=Math.floor(Math.random()*contents.length)
	//if element hasn't been marked as "selected"
	if (contents[random]!="selected"){
		document.write(contents[random]+spacing)
		//mark element as selected
		contents[random]="selected"
		i++
	}
}

This robust technique can be used to mix up the ordinal order of any group of values, such as a pool of lotto numbers.

Here is a second example that randomizes the display position of a group of button links: