I made a javascript function to change the background color to a random color every few seconds but it's not working. It changes the color on the click but not changing every few seconds. I want the background to change every few seconds. I'm testing it on one div with an onclick event. I don't want to use jQuery either. Thanks for your help!
index.html
<html>
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
<body>
<div id="div" onclick="timeChange()"></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<script src="myScript.js">
</script>
</body>
</html>
myScript.js
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
function changeDivColor() {
var div = document.getElementById("div");
var color = getRandomColor();
div.style.backgroundColor = color;
}
function timeChange() {
window.setInterval(changeDivColor(), 2000);
}
main.css
div {
float: left;
width: 200px;
height: 200px;
background-color: black;
margin-bottom: 20px;
margin-right: 20px;
}
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
function changeDivColor() {
var div = document.getElementById("div");
var color = getRandomColor();
div.style.backgroundColor = color;
}
function timeChange() {
window.setInterval(changeDivColor, 2000);
}
div {
float: left;
width: 200px;
height: 200px;
background-color: black;
margin-bottom: 20px;
margin-right: 20px;
}
<div id="div" onclick="timeChange()"></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
setInterval takes a function:
window.setInterval(changeDivColor, 2000); vs window.setInterval(changeDivColor(), 2000);
Create the interval on window.onload. I assigned the interval it changed to a variable, you can later use this to clear the interval if you wanted.
window.onload = function() {
var intervalChange = setInterval(changeDivColor, 2000);
}
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
function changeDivColor() {
var div = document.getElementById('div');
var color = getRandomColor();
div.style.backgroundColor = color;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With