Freelance Web Developer

Apr 7, 2010

Go random with JavaScript

One day, you must need code to get a random number, or values, in your program. Suppose you code for a game such as backgammon requires a roll of some dice on each move. Since there are 6 numbers on each die, you could calculate each roll by finding a random number from 1 to 6 for each die.
Today you will learn going random with JavaScript.


In the dreamnight animation we needed random positions and random colors for bubbles.


The random() method returns a random number between 0 and 1.

Generating random number less than M

 var randomnumber Math.floor(Math.random()*(M + 1));

This will generate no between 0 and M

Generating random number between higher and lower

 parseInt(rand_no Math.floor((higher - (lower 1)) * Math.random()) + lower); 

Generating random colors


OR if you need it in hex -

 Math.round(0xffffff Math.random()).toString(16

I hope now you are able to solve your problem you googled.


If this article helped you and you are feeling very Thankful. You can send me Bitcoins

By :