JQuery – Randomize Anything – Random Numbers with Random Colors

Some years ago, while I was writing my master thesis (I have two of them in two different languages), I remember that I was told that I should write something that is not written before and I should convince the reader why it is interesting. Now, I do not have to convince the reader anything, I simply code what I like and what I am currently learning. Thus, if you write “random jQuery” in google you would probably get about 3 pages of great ways to make ransoms in jQuery.

Anyway, I wanted to receive a way to make a random number in random font and background color. Thus, I have received the following result:random_numbers_random_colors

This article would be published on national holiday of Bulgaria, thus happy union day! Especially for the national holiday I have played with the random to achieve a result like this:

random_numbers_random_colors_colors

The question is how? 🙂 With jQuery of course.

Here comes the code:

<html>
<head>
    <title>JQ 10</title>
    <script src="https://code.jquery.com/jquery-1.10.1.min.js"></script>
    <script>
        $(document).ready(function () {  
            $("div").each(function(i){
                $("div").eq(i).html(Math.random());
                var colors = ["blue","orange","gray","red","purple","white","green","AliceBlue","gold","SeaShell"];
                var random_back = colors[Math.floor(Math.random() * colors.length)];
                $('div').eq(i).css('background-color',random_back);
                var random_font = colors[Math.floor(Math.random() * colors.length)];
                $('div').eq(i).css('color',random_font);                
            })
        });
    </script>
</head>
<body>
    <ul>
        <li><div></div></li>
        <li><div></div></li>
        <li><div></div></li>
        <li><div></div></li>
        <li><div></div></li>
        <li><div></div></li>
    </ul>
</body>
</html>

Here is the code in GitHub.

That is all! 🙂