Saturday, 22 August 2015

Generate Random Colors in Javascript

<html5>
    <script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
    <script type="text/javascript">
        var colorsList = new Array();
        function getRandomColor() {
            var letters = '0123456789ABCDEF'.split('');
            var color = '#';
            for (var i = 0; i < 6; i++) {
                color += letters[Math.floor(Math.random() * 16)];
            }
            return color;
        }
        function getRandomColorNotInList(colorsListToSkip) {
            do {
                color = getRandomColor();
            } while (jQuery.inArray(color, colorsListToSkip) != -1);
            return color;
        }

        $(document).ready(function () {
            for (i = 0; i < 1000; i++) {
                var color = getRandomColorNotInList(colorsList);
                colorsList.push(color);
            }
            colorsList.sort();
            var len = colorsList.length;
            console.info(" len = " + len);
            for (i = 0; i < len; i++) {
                $(document.body).append(''; width:200px; height:50px;  display:inline-block;">' + colorsList[i] + '
');               
            }
        });

    </script>

    <body>

    </body>

</html5>

No comments:

Post a Comment