Before reading this code you should know about
- Javascript Math floor function
- Javascript Math Radom function
- HTML DOM
- For loop
In this code we will change the background color from the selected list of colors.
<!DOCTYPE html>
<html lang="en">
<body>
<div id="col">
<h3>Javascript code to change background color every 5 seconds</h3>
</div>
<style>
#col {
position: absolute;
width: 100%;
height:100%;
background-color: blue;
}
</style>
<script>
const div = document.getElementById("col");
function setColor()
{
colors = ["blue","red","yellow","green","orange","pink"]
div.style.backgroundColor = colors[Math.floor(Math.random()*6)];
}
setInterval(setColor, 5000);
</script>
</body>
</html>
In this code, we will change the background color by generating random colors using the function.
<!DOCTYPE html>
<html lang="en">
<body>
<div id="col">
<h3>Javascript code to change background color every 5 seconds</h3>
</div>
<style>
#col {
position: absolute;
width: 100%;
height:100%;
background-color: blue;
}
</style>
<script>
const div = document.getElementById("col");
function color()
{
var char = "0123456789ABCDEF";
var result = '#';
for(var i = 0; i < 6; i++)
{
result += char[Math.floor(Math.random()*16)];
}
return result;
}
function setColor()
{
div.style.backgroundColor = color();
}
setInterval(setColor, 5000);
</script>
</body>
</html>