Question

I am a newbie and I am trying to create an HTML page with buttons that have random background colors based on colors in an array. This is what I have right now (although it doesn't work). I am hoping someone can give me advice on how to fix this so that it does what I want.

    #button {
            width: 100px;
            height: 100px;
        }

    </style>
</head>

<body>
    <div id="testForm">
        <button id="button">
            Testing
        </button>
    </div>


    <script type="text/javascript">

        $(document).ready(function()
        {
            var myColors = new Array();
            myColors[0] = "#2672EC";
            myColors[1] = "#97009F";
            myColors[2] = "#094DB5";
            myColors[3] = "#00A300";
            myColors[4] = "#DA532C";
            myColors[5] = "#AF1A3F";
            myColors[6] = "#613CBC";
            myColors[7] = "#008AD2";

            var rand = Math.floor(Math.random()*myColors.length); 
            $('#button').css("background-color", myColors[rand]); 
        }


    </script>
Was it helpful?

Solution 2

Close the ready function

DEMO

 $(document).ready(function()
            {
                var myColors = new Array();
                myColors[0] = "#2672EC";
                myColors[1] = "#97009F";
                myColors[2] = "#094DB5";
                myColors[3] = "#00A300";
                myColors[4] = "#DA532C";
                myColors[5] = "#AF1A3F";
                myColors[6] = "#613CBC";
                myColors[7] = "#008AD2";

                var rand = Math.floor(Math.random()*myColors.length); 
                $('#button').css("background-color", myColors[rand]); 
            });  //missed to close

OTHER TIPS

var myArray = [ "#97009F","#094DB5","#00A300","#DA532C","#AF1A3F","#613CBC","#008AD2"];
var rand = myArray[Math.floor(Math.random() * myArray.length)];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top