33

Change Background Color Every Seconds in JavaScript

 5 years ago
source link: https://www.tuicool.com/articles/hit/ui6namB
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

In this tutorial, I am going to show you a very cool thing you can do with JavaScript. All of us know about the background color of a webpage. We can change the background color as well. But have you ever thought of changing this background color with JavaScript? I think most of us can do this, But here you gonna learn how to change background color every seconds in JavaScript automatically with random color each time.

Before going to this tutorial I would like to recommend you to read Generate random hex CSS color code in JavaScript

Steps to be followed:

  1. Create a random hex color with JavaScript
  2. Use the random color as background color with JavaScript
  3. Finally, Change this color with the setInterval method with a particular Interval period

Don’t worry you will get to learn all of these, one by one.

Generate a random hex color:

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

This will create a random number in between 0 to 16777215 and toString method is used to convert the random number to hex.

We need hex here because we are going to use hex color code. ( eg, #ffffff )

document.body.style.backgroundColor = "#"+randomColor;

Now this line will change the background color to a random color.

Now we just need to use the setInterval method to change the background color automatically in every n second.

Change background color every seconds in JavaScript with a random hex color

setInterval(
function () {
  var randomColor = Math.floor(Math.random()*16777215).toString(16);
  document.body.style.backgroundColor = "#"+randomColor;
},1000);

Here I have used 1000 milliseconds because I want to change the background color in every 1 second. You can use as per your need. ( 1 second is equal to 1000 milliseconds )

To know more about setInterval Run your JavaScript code every n seconds using setInterval() method

How to stop JavaScript setInterval() after a certain time period?

Here is the full code, You can test it on your browser.

<!DOCTYPE html>
<html>
<head>
  <title>Change bg color every 1 seconds</title>
</head>
<body>
<h1>Background Color is being changed every 1 seconds</h1>
<script>
setInterval(
function () {
  var randomColor = Math.floor(Math.random()*16777215).toString(16);
  document.body.style.backgroundColor = "#"+randomColor;
},1000);
</script>
</body>
</html>

You may also read,

How to stop JavaScript setInterval() after a certain time period?


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK