0
6.0kviews
Write JavaScript program to change background color continuously using button.
1 Answer
written 6.3 years ago by |
Math.floor(Math.random() * 10)
selects any random number from 0 to 9. According to randomly selected number and color value associated with that number is set as background color for 500 ms only. <!DOCTYPE html> <html> <head> <title>Background Color Changer</title> <script lang="text/javascript"> function bgcolor() { loopID = window.setTimeout("bgcolor()",500); // 500 milliseconds delay var index = Math.floor(Math.random() * 10); var ColorValue = "FFFFFF"; // default color - white (index = 0) if(index == 1) ColorValue = "FFCCCC"; //peach if(index == 2) ColorValue = "CCAFFF"; //violet if(index == 3) ColorValue = "A6BEFF"; //lt blue if(index == 4) ColorValue = "99FFFF"; //cyan if(index == 5) ColorValue = "D5CCBB"; //tan if(index == 6) ColorValue = "99FF99"; //lt green if(index == 7) ColorValue = "FFFF99"; //lt yellow if(index == 8) ColorValue = "FFCC99"; //lt orange if(index == 9) ColorValue = "CCCCCC"; //lt grey document.getElementsByTagName("body")[0].style.backgroundColor = "#" + ColorValue; } function stopcolor() { document.body.style.backgroundColor="white"; clearTimeout(loopID); } </script> </head> <body> <center><br> <input type="button" value= "Color Changing Start" onclick="bgcolor()"> <br><br> <input type="button" value= "Color Changing Stop" onclick="stopcolor()"> </center> </body> </html>