In a previous tutorial, I showed some inventive uses of the PHP rand and switch functions. You can do all this (and more) with JavaScript. So, for the sake of balance, here is how you make a Magic 8 Ball in JavaScript.

Making a Magic 8 Ball

To make out JavaScript Magic 8 Ball, we will be using the Math.random() and Math.floor() functions to generate a random number and to round it down to the nearest integer.

<script type="text/javascript">
//Define the variable results as one of the 20 answers
var results = [
"It is certain",
"It is decidedly so",
"Without a doubt",
"Yes – definitely",
"You may rely on it",
"As I see it, yes",
"Outlook good",
"Signs point to yes",
"Yes",
"Reply hazy, try again",
"Ask again later",
"Better not tell you now",
"Cannot predict now",
"Concentrate and ask again",
"Don't count on it",
"My reply is no",
"My sources say no",
"Outlook not so good",
"Very doubtful"];
//Define the variable randresults as a randomly generated number
//... between 0 and 19 (where *19 defines the maximum number)
var randresults = Math.floor(
 Math.random()
 *19)
document.write(results[randresults]);
</script>

See this script in action »

Taking it further

In my tutorial of random things in PHP, I covered several examples of how the random number function could be used. Each of them is also possible using the JavaScript method above. Using that example as a starting point, why not have a go and see what you can come up with!

Tagged with: