Economy of Code

Programmers strive for economy of code. If a function can be re-used, it should be. Webpage markup is no exception. Any dedicated web designer spends a significant amount of time preparing their web document; therefore, any shortcuts are highly appreciated and speed up the process. Javascript is convenient in that it allows the creation of reusable functions. One of these, shown below, allows the long, complicated JavaScript tag to be replaced with <script language="JavaScript">randomLink("Example Link");</script>;

Header Code Block

<html>
<head>
...
<script language="JavaScript">
<!––
	link = new Array;
	link[1]="random/end1.html";
	link[2]="random/end2.html";
	link[3]="random/end3.html";

	function randomLink(linkText) {
		random_num = (Math.round((Math.random()*2)+1));
		document.write("<a href=\"" + link[random_num]
			+ "\">Example Link</a>");
	}
––>
</script>
</head>

Body Code Block

Once you have that in place, you can change the "2" and the "Example Link" string to alter the range of the random number (n+1, whatever you choose) or what the displayed text is. In the body of your code, simply use the string mentioned in the first paragraph, just as you see it. In this case it doesn't matter what you put inside randomLink("Example Text"), as long as it's in quotation marks. See below for a demonstration.

>>> Return to Random Links >>>