Pages

Random Number generator in javascript


How to generate a random number in javascript.html

Ok so , here I am going to demonstrate hos to generate a random number in javascript,
using Math.random() function, and how to set a range to it,

First, as always lets set up the html file where the javascript file,
is going to get called,here it is,

<html>
<head>
<title>Random_Number</title>
<script type="text/javascript" src="1.js">
</script>
</head>
<body>
<font style="font-size: 200pt" color=blue>
    <a href="1.html">
        <dfn title="click to generate another random number">
            <h1 align="center" id="random"></h1>
        </dfn>
    </a>
</font>
</body>
</html>

Here I have done someting cool, I have used font tag, dfn tag and ahref tag,id tag and H1 tag all
together, to create , what i like to call, CREATIVE MAYHEM,
when you see this at work , you will love it,

and here is the javascript file,

window.onload = randomnum;


function randomnum(){
document.getElementById("random").innerHTML = 
       Math.floor(Math.random() * 101);
}

here I called the inbuilt function of javascript Math.random().
One thing to pay attention to here is that,
math.random() returns a random number between 0.0 to 0.99999(many more 9s)
for instance, its something like, 0.678923424..
so I multiplied this "ugly" looking decimal number by 100 and then floored it,
by using yet another javascript inbuilt function called, Math.floor.
and the result a handsome whole number.

now How to set up the range of the random number?

here i wanted to generate a random number between 0 and 100,
so i did
Math.floor(Math.random() * 101)

suppose you want a random number between 0 and 75, so all you got to do is,
Math.floor(Math.random() * 76)

suppose you want a random number from 1 to 10, then you do this,
Math.floor(Math.random() * 10) + 1

you can have a look at how this looks like here,
(do have a look , I created it with great detail)