Make your own free website on Tripod.com

[an error occurred while processing this directive]

Site Menu

HTML
Learn all about HTML, how to format text, add images, create tables, meta taga, and more!
.
JavaScript
Get the low down on JavaScript. See how to create popular JavaScript applications like drop down menus, clocks, dynamic messages, popup boxes, and more.
.
CGI
Concise, easy to follow introdction to CGI and how to install CGI scripts.
.
Web Design
A miscellanous section that includes various web design tutorials

 

123 Web Design!

Displaying a random message

I get a lot of emails asking me stuff like: "How do I display a random quote on my page?", or "Is it possible to have a random image show up each time the surfer reloads the page?" The answer? No problemo! JavaScript can be used to easily accomplish just that.

The below's a "random" quote example, where a quote out of three is randomly displayed each time this page is loaded (Reload this web page to see another quote):

"You can count on it"

Here's the source code used:

<script>
var whichquote=Math.round(Math.random())*3
if (whichquote<=1)
document.write('"You can take away my life, but you can never take away my freedom!"')
else if (whichquote<=2)
document.write('"I\'ll be back"')
else if (whichquote<=3)
document.write('"You can count on it"')
</script>

The key here is the code:

var whichquote=Math.round(Math.random())*3

I'll explain this code by breaking it down: Math.random() is a JavaScript method, and always generates a real number between 0 and 1. Math.round() rounds that number to an integer. By multiplying that number by 3, I always get a random number that's between 0 and 3. Why 3? Because I have three quotes I want to randomly display, so I need three random "slots". If you have 5 quotes, just multiple the code by 5 instead.

Now, quotes are great, but what if you want to display a random image? Simple. Just change the text to the <img> tag:

<script>
var whichquote=Math.round(Math.random())*3
if (whichquote<=1)
document.write('<img src="first.gif">')
else if (whichquote<=2)
document.write('<img src="second.gif">')
else if (whichquote<=3)
document.write('<img src="third.gif">')
</script>

Don't you just love JavaScript?