Hi, i am very new to javascript. I am pretty good with PHP, and have a solid understanding of HTML and CSS. I know the basics of js, and i am trying to make a script that will shift between background images for a div. From my understanding, this should make a the div dynamic in the sense that it will change color without reloading the whole page. When i execute this code it crashes firefox. If there is something wrong with the code, or if i was mistaken by thinking that i could make a dynamic part of the site with javascript, please tell me. I want to learn how to use javascript to make a part of a page dynamic. Here is my code: <html> <head> <script type="text/javascript"> function pausecomp(millis) { var date = new Date(); var curDate = null; do { curDate = new Date(); } while(curDate-date < millis); } function change_bgcolor() { color_arr = new Array('red', 'white', 'blue', 'green', 'brown', 'pink', 'orange'); num = 0; while(1) { color = color_arr[num]; elem = document.getElementById("box"); elem.style.backgroundColor = color; pausecomp(500); if(num <= 6) { num++ } else { num=0; } } } </script> </head> <body onload="change_bgcolor()"> <div id="box" style="background-color: blue; height: 200px; width: 400px;"> </div> </body> </html>
Hi there! No you were not mistaken. Javascript has a native timeout function that makes it easy to create these "rotate stuff" functions. I took the liberty to make some changes to your code. <html> <head> <script type="text/javascript"> // define some vars var iIdx = 0; var oTimer = null; function rotateColours() { // your array var aColourArray = new Array('yellow', 'red', 'grey', 'blue', 'green', 'brown', 'pink', 'orange'); // this gives you the length of the array - similar to php count() var iArrayLength = aColourArray.length; // see how many recursions has been made and when we reach the end // reset the index to start over from the first value if (iIdx >= iArrayLength) { iIdx = 0; } // do your thing document.getElementById('box').style.backgroundColor = aColourArray[iIdx]; // add to the index counter iIdx++; // make a recursive call every 500 milliseconds... oTimer = setTimeout('rotateColours()', 500); // why not return something :) return true; } </script> </head> <body onload="rotateColours()"> <div id="box"style="height: 200px; width: 400px;"></div> </body> </html> HTML: