spacer

Webref WebRef   Sitemap · Experts · Tools · Services · Newsletters · About i.com

Developer News
Microsoft Shows Some Ankle With Visual Studio
Gentoo Linux Cancels Distribution
It's Official: Windows 7 at PDC, WinHEC
JavaScript Tip of the Week for May 13, 1996: Random Quotes and Images

Ever wanted to make your site more random? Maybe you're just a random person. Whatever the case is, how about putting a random quote, image, or sound in your page. Be a little... unpredictable, so to speak. The most efficient way to do this is by using arrays. was randomly chosen from a list of four in an array. Exciting? No, but it gets better. Hear that background music (maybe it's still loading)? Well, that's randomly chosen too. Although this music doesn't go with this page, I think it's worth it to be unpredictable. Pretty much anything on this page could be randomly chosen. I could even splice together a random sentence using random nouns, adjectives, and verbs.



The first step is to create an array of words, quotes, images, or some other HTML related objects. To do this in Netscape 2.0, you need to use a small array object constructor function:
    function makeArray(){
    this.length = makeArray.arguments.length 
        for (var i = 0; i < this.length; i++)
        this[i + 1] = makeArray.arguments[i]
    }
Don't fret if you don't understand how it works, essentially what this does is take the arguments that you pass it and indexes them in the same fashion that an array does. You don't need to use an array constructor like this in Netscape 3.0 or IE 3.0 because they supports real arrays. But for the sake of backwards compatibility I use this one in most cases. Now that you (somewhat) understand how that function works, it's time to put it to use. Define what is going to be in the array: in the case of the four word array, the code looks like this:
    var wordArray = new makeArray('Oui', 'Yes', 'Da', 'Si');
Where "Oui", "Yes", etc. are all words that are going to be picked out of the wordArray array. The first word, "Oui", is element one in the array wordArray. The second word, "Yes", is element two in the array, and so on. To access the value of element one in wordArray, you would use this line of code:
    document.write (wordArray[1]);
This would display element one of the array, "Oui", on the page. Now that you know how to create and gather information from these arrays, it's time to randomize them. To randomize these words, or rather print them on the page randomly, you need a random number generator:
    function randNum (num) {
    var now = new Date();                                 <-- grab the cur time in msecs
    var rand = Math.round(num * Math.cos(now.getTime())); <-- find the cos of the time
    if (rand < 0) rand = - rand; if (rand == 0) rand++;       and mult by your num  
    return rand;                                          <-- return the random number
    }
When you pass this function a number, it will return a pseudo-random number from one to the value of the number you passed it. I must admit, there are better random number generators than this one, but for the time being this will do. Now you need to apply this random number generator to the array of words, but how? Well, take the total number of words in the array, determined using the length property, and send that to the random number generator:
    randNum(wordArray.length)
Now you have a random number, but you need to grab the element that corresponds to that random number out of the array. Since the random number returned is one through four, you can use that to access the elements of the array. Put that code where the element of the array goes and presto; random words:
    document.write (wordArray[randNum(wordArray.length)]) 
Actually, you don't have to use just words, you can use an image, embed, or anything you want. Simply plug your objects directly into the array. If you put a few embeds in the array, your page would play a random music file:
var musicArray = new MakeArray("<EMBED AUTOSTART = TRUE HIDDEN = TRUE SRC = 'canon.mid'>",
                               "<EMBED AUTOSTART = TRUE HIDDEN = TRUE SRC = 'jtotw.mid'>",
                               "<EMBED AUTOSTART = TRUE HIDDEN = TRUE SRC = 'prelude.mid'>",
                               "<EMBED AUTOSTART = TRUE HIDDEN = TRUE SRC = 'take5.mid'>") 
This would give you an array of four embeds, to print them out in a random fashion just follow the same steps as you did with the words. Keep in mind that this array is named musicArray, not wordArray, so the code must reflect that.

Source



JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
IBM Whitepaper: Innovative Collaboration to Advance Your Business
Internet.com eBook: Real Life Rails
Avaya Article: Call Control XML - Powerful, Standards-Based Call Control
Internet.com eBook: The Pros and Cons of Outsourcing
Go Parallel Article: Scalable Parallelism with Intel(R) Threading Building Blocks
Internet.com eBook: Best Practices for Developing a Web Site
IBM CXO Whitepaper: The 2008 Global CEO Study "The Enterprise of the Future"
Avaya Article: Call Control XML in Action - A CCXML Auto Attendant
Go Parallel Article: James Reinders on the Intel Parallel Studio Beta Program
IBM CXO Whitepaper: Unlocking the DNA of the Adaptable Workforce--The Global Human Capital Study 2008
Adobe Acrobat Connect Pro: Web Conferencing and eLearning Whitepapers
Go Parallel Article: Getting Started with TBB on Windows
HP eBook: Storage Networking , Part 1
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Go Parallel Video: Intel(R) Threading Building Blocks: A New Method for Threading in C++
HP Video: Is Your Data Center Ready for a Real World Disaster?
Microsoft Partner Portal Video: Microsoft Gold Certified Partners Build Successful Practices
HP On Demand Webcast: Virtualization in Action
Go Parallel Video: Performance and Threading Tools for Game Developers
Rackspace Hosting Center: Customer Videos
Intel vPro Developer Virtual Bootcamp
HP Disaster-Proof Solutions eSeminar
HP On Demand Webcast: Discover the Benefits of Virtualization
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Microsoft Download: Silverlight 2 Software Development Kit Beta 2
30-Day Trial: SPAMfighter Exchange Module
Red Gate Download: SQL Toolbelt
Iron Speed Designer Application Generator
Microsoft Download: Silverlight 2 Beta 2 Runtime
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
IBM IT Innovation Article: Green Servers Provide a Competitive Advantage
Microsoft Article: Expression Web 2 for PHP Developers--Simplify Your PHP Applications
Featured Algorithm: Intel Threading Building Blocks - parallel_reduce
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES
webref The latest from WebReference.com Browse >
Controllers: Programming Application Logic - Part 2 · How to Use JavaScript to Validate Form Data · Controllers: Programming Application Logic
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Sprint Launches Mobile WiMAX Network · Albatron Downsizes with the KI780G Mini-ITX Motherboard · Can't Find a Wi-Fi Network? Make Your Own.