Random Strings [Source]

Last updated: 08.05.2002


Source code for the Random Strings script to display randomly-selected strings.


<SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript">
    <!--
        // Trivial and pointless little JavaScript to interpolate random 
        // strings into a page.
    
    var sc = 10;                    // Number of alternative strings
    var s = new Array(sc);          // Array to hold alternative strings
    
    // String definitions. There should be exactly 'sc' strings, numbered
    // from 0 to (sc - 1). You can embed markup in the strings, provided
    // you're careful to escape any double quotes. Note that if you fail
    // to define enough strings, you'll get 'undefined' appearing in place
    // of the string, or possibly even a security violation, which tends
    // to be unaesthetic.
    
    s[0] = "She won't live, of course. But then again ... who does?";
    s[1] = "I seem to be having tremendous difficulty with my lifestyle.";
    s[2] = "Frog blast the vent core!";
    s[3] = "Pizza is a lot like sex. When it's good, it's really good. " +
    	   "When it's bad, it's still pretty good.";
    s[4] = "unix soit qui mal y pense";
    s[5] = "Wriggling grunion in your slipstream";
    s[6] = "I'm shocked to hear it. The Hyperdyne 400 series always " +
    		"were a bit twitchy.";
    s[7] = "I have the greatest enthusiasm for our mission, Dave.";
    s[8] = "Do not taunt Happy Fun Ball.";
    s[9] = "Do not look into laser with remaining good eye.";
    
    // pickRandom - Return a random number in a given range. If we're running
    // on an older browser that doesn't support 'Math.random()', we can fake
    // it by using the current time. This isn't ideal for mission-critical
    // security applications, but it's fine here. Note that we divide the
    // current time by 1000 to get rid of the milliseconds which Navigator
    // doesn't seem to take into account.
    
    function pickRandom(range) {
        if (Math.random)
            return Math.round(Math.random() * (range-1));
        else {
            var now = new Date();
            return (now.getTime() / 1000) % range;
        }
    }
    
    // Write the string into the document. The "<BLOCKQUOTE>" tags are just 
    // for formatting; you can put as much or as little HTML around these 
    // strings as you like.
    
    var choice = pickRandom(sc);
    document.writeln("<TABLE WIDTH=460 ALIGN=CENTER><TR><TD>" +
                     "<BLOCKQUOTE><BIG><B>" + s[choice] + 
                     "<" + "/B><" + "/BIG><" + "/BLOCKQUOTE>" +
                     "<" + "/TD><" + "/TR><" + "/TABLE>");
    
    // --></SCRIPT>

[raingod:resources:javascript] -- [up][links][home]