Hacks: A Random Link Button

06/21/2003

Some people read a weblog because they like the person who runs it. Maybe they think that person is a highly entertaining, witty and exciting individual. On the other hand, many weblogs are run by geeks (including this one). If you’re a social no-hoper – what are you to do? How do you get people to come to your site and experience the wonderful links you’ve found without forcing them to plough through all the rubbish you feel obliged to write?

The ‘random link’ code does just what it says on the tin. When your visitor clicks onto it, it gives every link contained on that page of your weblog a number, chooses a random one and then follows it. No muss, no fuss…

In order to put a ‘random link’ button on your weblog, you need to insert this simple piece of javascript into the of your Blogger or Moveable Type template:

<script language="JavaScript">
<!--
// Surprise me button
function goRandom()
{
var numLinks = document.links.length;
var randomNum = (numLinks - 1) * Math.random();
randomNum = Math.round(randomNum);
window.location.href = document.links[randomNum].href;
}
//--></script>

Now you only need to insert the link itself into your template to help take even the slightest effort out of your visitor’s daily visits:

<a href="javascript:goRandom()"">Random Link</a>

This hack was originally supposed to appear in the ill-fated O’Reilly “Blogging Hacks” book. I’ll be putting all my contributions online over the next few days / weeks.