View Full Version : random questions
the_bob
01-06-2004, 03:17 AM
ok, i've found my huge lack of java scripting knowledge. I have no clue how to use random things. For example, how would you be able to have a list of URLS but only one would pop-up when the site loads? (OnLoad)
fredmv
01-06-2004, 03:21 AM
<script type="text/javascript">
//<![CDATA[
var uri =
[
'http://www.yahoo.com/',
'http://www.google.com/',
'http://www.hotbot.com/'
];
onload = function()
{
window.open(uri[Math.floor(Math.random()*uri.length)]);
}
//]]>
</script>
Math.random() function generates a random number between 0 and 1 (with more or less digits decimals - usually 16).
To obtain a random weighed number between 0 and N you simply multiply the genuine random number with the difference (N-0) and round the result
To round you may use different functions such as
Math.round - automatic
Math.floor - rounds down
Math.ceil - rounds up
It looks like using Math.floor or Math.ceil is a better choise than Math.round (they give a "more randomized" weighed numbers). Math.floor has another advantage, see below.
In your example, you need to obtain a random weighed number between 0 and the lenght of your object type (the number of the objects). Why not lenght-1?... Becouse Math.floor will round for instance 2.99999999999 as 2, and never reach the full 3.
So here we are with the explanation for the fredmv's code :thumbsup:
the_bob
01-06-2004, 11:54 AM
fred, thanks for the code, thats great!
and Kor, Thanks for the explanation. Random numbers are probably one of the most commonly used things in java script. I really appreciate it.
but one more question, what does the [CDATA[ in freds code do?
Maybe fredmv used an editor with an XML validator, as CDATA sections are used to escape blocks of text containing characters which would otherwise be recognized as markup...
fredmv
01-06-2004, 08:14 PM
Good explanations Kor (good guess about the XML validator, however, I manually add the CDATA section in scripts or CSS whenever I use embedded code, however, I usually make the code external anyway)... :thumbsup:
the_bob
01-06-2004, 08:18 PM
oh, thanks, both of you
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.