0
5.8kviews
Write JavaScript program to change background color continuously using button.
1 Answer
1
259views
  • Method setTimeout() set the time of 500 ms for background color change.
  • Function 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.
  • Background color change after every 500 ms based on randomly selected number.
  • When user click on start button background color changing starts and stops only when user click on stop button.
  • Program :
<!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>
Please log in to add an answer.