Friday, July 15, 2011

Generate random number with javascript

We can generate a random number easily using javascript. Random number can be uses in many purposes, from setting the dynamic timeout, choosing arrays, IF conditional, etc. In this tutorial I'll use 2 main javascript method, math.floor() and math.random().
Math.floor() to round the number example from 5,4 to 5. Math.random() to generate a random number.


Here is the example script. Prototype one... :D
<script>
function random(){
var out = (Math.floor( Math.random() * 1000 ));
document.getElementById("test").innerHTML = out;
}
</script>
<div id='test'/>
<input type='button' onclick='random();' value='random'/>


How it works:
- when you click random button, function random fired.
- (Math.floor( Math.random() * 1000 ) ); will generate a random number from 0-1000.
You can also add an operator to it for example (Math.floor( Math.random() * 1000 + 500) );
- document.getElementById...... is use to write the result to selected DIV so you can see the output of the script.

Try it:



OK, that's it. you can apply this random number generator to your project... :D

No comments:

Post a Comment