Web Hosting
We've partnered with HostGator for reliable, affordable hosting starting at $3.95/mon. Use coupon code "javascriptkit25" for 25% off any package.

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:

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

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=

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


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

Copyright 1997-2014 JavaScript Kit. NO PART may be reproduced without author's permission.