Home > OS >  How to make the div box randomly change color every 1000 millisecond with HTML Javascript?
How to make the div box randomly change color every 1000 millisecond with HTML Javascript?

Time:01-21

I've been trying to figure out how to make the div box randomly change color every 1000 millisecond. This is my attempt of function changeColor JavaScript file:

myInterval = setInterval(changeColor, 1000);
var box = document.getElementById("box");

function changeColor() {
  var randomColor = Math.floor(Math.random() * 16777215).toString(16);

  box.style.backgroundColor = "#"   randomColor;

  //let x = document.getElementById('contents');
  //x.style.backgroundColor = x.style.backgroundColor == "yellow" ? "pink" : "yellow";
}
<div id="box">This is some text in a div element.</div>

CodePudding user response:

Like this way

var div = document.querySelector(".test");

setInterval(() => {
  div.style.background = `#${getColor()}`;
}, 1000)

function getColor() {    
  return Math.floor(Math.random()*16777215).toString(16);
}

CodePudding user response:

I have attached the javascript function to change the colour of the randomly for every 1000 milliseconds.

<!DOCTYPE html>
<html>
<head>
  <title>Change bg color every 1 seconds</title>
</head>
<body>
<div id="box">This is some text in a div element.</div>
<script>
setInterval(
function () {
  var randomColor = Math.floor(Math.random()*16777215).toString(16);
  document.getElementById("box").style.backgroundColor = "#" randomColor;
},1000);
</script>
</body>
</html>

  •  Tags:  
  • Related