tjmbc Posted December 18, 2008 Share Posted December 18, 2008 I am trying to write a simple function that makes a div change background colors randomly. Here's the code so far: function setBackground() { var digit = new array('0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'); //Creates an array with hex digits. digit.sort(function() {return 0.5 - Math.random()}); //Randomizes the above array. clr = "+" + digit[0] + digit[1] + digit[2] + digit[3] + digit[4] + digit[5]; //Puts the array in color form (ie. #00ff00). boxdiv.style.backgroundColor = clr; //Sets the background color of the div tag. } The code doesn't work. If I put the line... boxdiv.style.backgroundColor = "#00ff00"; ... it will change the color. (The function is tied to a buttons 'onClick' event). Anyone know what I'm missing? Quote Link to comment https://forums.phpfreaks.com/topic/137579-why-doesnt-this-work/ Share on other sites More sharing options...
rhodesa Posted December 18, 2008 Share Posted December 18, 2008 Array needs to be capitalized, and you can't just call boxdiv. If it's on the onclick for the element, just pass itself to the function, like so: <script type="text/javascript"> function setBackground(ele) { var digit = new Array('0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'); //Creates an array with hex digits. digit.sort(function() {return 0.5 - Math.random()}); //Randomizes the above array. clr = "#" + digit[0] + digit[1] + digit[2] + digit[3] + digit[4] + digit[5]; //Puts the array in color form (ie. #00ff00). ele.style.backgroundColor = clr; //Sets the background color of the div tag. } </script> <div style="width:100px;height:100px;" onclick="setBackground(this)"></div> Quote Link to comment https://forums.phpfreaks.com/topic/137579-why-doesnt-this-work/#findComment-719071 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.