Categories:

Creating a random link out of all of the links in a document

Using the Math.random() method, we can create a generic random link that uses all of the links in the document as its "ammunition". In other words, a random link that randomly chooses from one of the links on the page- any page the script is on- to go to. Lets see how a script like this is implemented:

<script>
function random_all(){
	var myrandom=Math.round(Math.random()*(document.links.length-1))
	window.location=document.links[myrandom].href
}
</script>

The above script may be short, but it is very powerful! It can be inserted into any document to instantly create a random link out of all of the links in the document. Before we go any further, lets put the above script in a document and see it in action:

The technique used to create this script is quite simple. By using the length property of the links object, we first generated a random number that falls in the range of 0 and the index number of the last link in the document:

var myrandom=
Math.round(Math.random()*(document.links.length-1))

Then by using this random number as an index number to reference a random link in the document:

window.location=document.links[myrandom].href

We create a random link that draws a url out of all of the links in the document!