first of all
although the code u found to generate a random number works fine if you only have to produce one random number, it will have problems when ur trying to produce, say, three random numbers. you'll see as i descuss. the best thing to do would be to put the random number code into a value returning function so your code should look like this:
- Code: Select all
function randomNumber(){
return Math.floor(Math.random()*51);
}
the reason to do this is because if u store it into a variable, the browser will only find one random number and store it into the variable "randomnumber" once and the number becomes fixed. the problem with that is that you get the same number any time u call the "randomnumber" variable. if u put it in a function like the code i gave you, the browser will wait until the function is called to exicure the random numer generating code which means the every time u call "randomnumber()" as a function, the code will be re-executed creating a new number each time. which is what you want.
as to were to put the code, anywere between and ,script. tags is acceptable, but the normal thing is between those tags inside the head tag. like this:
- Code: Select all
<html>
<head>
..other stuff in head tag...
<script language="javascript">
function randomNumber(){
return Math.floor(Math.random()*51);
}
</script>
</head>
...and so on
whenever you want to display another random number, just call it inside a document.write() method to output it.
put this code wherever on your page you want a random number:
- Code: Select all
<script language="javascript">document.write(randomnumber());</script>