How can I change the background color in HTML using JavaScript?
this webpage changes backgrounder color randomly. I am having problems with the same as "#title" but the color remains the same.
please, help
thank
JavaScript code:
function setbackground()
{
window.setTimeout( "setbackground()", 80); // milliseconds delay
var index = Math.round(Math.random() * 9);
var ColorValue = "FFFFFF"; // default color - white (index = 0)
if(index == 1)
ColorValue = "66FF33";
if(index == 2)
ColorValue = "FF0000";
if(index == 3)
ColorValue = "FF00FF";
if(index == 4)
ColorValue = "0000FF";
if(index == 5)
ColorValue = "00FFFF";
if(index == 6)
ColorValue = "FFFF00";
if(index == 7)
ColorValue = "CC66FF";
if(index == 8)
ColorValue = "3366FF";
if(index == 9)
ColorValue = "CCCCCC";
document.getElementsByTagName("body")[0].style.backgroundColor = "#" + ColorValue;
}
function setbackgroundTitle()
{
window.setTimeout( "setbackgroundTitle()", 600); // milliseconds delay
var index = Math.round(Math.random() * 4);
var ColorValue = "FFFFFF"; // default color - white (index = 0)
if(index == 1)
ColorValue = "66FF33";
if(index == 2)
ColorValue = "FF0000";
if(index == 3)
ColorValue = "FF00FF";
if(index == 4)
ColorValue = "0000FF";
document.getElementById("title")[0].style.backgroundColor = "#" + ColorValue;
}
CSS code:
#title{
background-color:#11f22f;
height:300px;
width:400px;
margin:25px auto 0 auto;
-moz-border-radius:25px;
-webkit-border-radius:25px;
}
html Code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>HomeWork</title>
<script type="text/javascript" src="crazy.js"> </script>
<link rel="stylesheet" type="text/css" href="HomeWork2.css" />
</head>
<body>
<body onload="setbackground();">
<div id="title" onload="setbackgroundTitle();"> hjhjhkj dfvdfsv dfgvkdfsk dfs</div>
</body>
</html>
source to share
First copy the patch error: instead document.getElementById("title")[0].style.backgroundColor = "#" + ColorValue;
should be document.getElementById("title").style.backgroundColor = "#" + ColorValue;
According to this How to make a div function onload? does not work. I put everything in setbackground () and it works;)
source to share
The problem might be that the DOM was not loaded when the script was run.
Correct your function, you are accepting the output document.getElementById("title")
as an array, but it isn't.
document.getElementById("title").style.backgroundColor = "#" + ColorValue;
And call it on the onload event to ensure that the DOM is loaded correctly when the script runs
window.onload = function() {
setbackgroundTitle();
};
source to share