DEV Community

Cover image for How To Randomly Change Background Color in Javascript.
 Faith Pueneh
Faith Pueneh

Posted on • Updated on

How To Randomly Change Background Color in Javascript.

Introduction:

In this article, you will learn how to change your background color randomly by using the Javascript built-in Math functions and the hexadecimal color code. You will learn how to use the onClick event function to trigger the button’s action. Changing a background color randomly can be interesting, there are a couple of web applications that this has been used on.

Prerequisite:

  • Have a good knowledge of HTML
  • Have a good knowledge of CSS
  • Have a good knowledge of Javascript.

HTML Structure:

To begin the project create an HTML file called index.html.

  • In the body tag, create a div with a class called ‘container’.
  • Create another div in the first div.
  • Create an h1 tag with its title.
  • Create an h2 tag with a span tag inside of it. Give the span tag an id called ‘colorCode’ . the span tag holds the random hexadecimal number whenever it is called.
  • Create a button element with a class called btn- color as seen below
...
 <body>
    <div class="container">
      <div>
        <h1>Click The Button Below To Generate A Random Hex Color Code.</h1>
        <h2>Your backgroud color is : # <span id="colorCode">0f5257</span></h2>
        <button  class="btn-color">
          Generate Color
        </button>
      </div>
    </div>

  </body>
...
Enter fullscreen mode Exit fullscreen mode

CSS Structure:

Create a CSS folder and in it create a file called style.css, this is where you will write all your CSS. To link your CSS to your HTML, in your HTML file, add the following to the head tag.

...
<link rel="stylesheet" href="Css/style.css" />
...
Enter fullscreen mode Exit fullscreen mode

Go back to your CSS file and write down the following code. Please note that you are to start building this project for mobile screens and use a media query to style for larger screens. To make this project responsive on larger screens, you will use a min-width of 992px as seen below.

body {
  padding: 0;
  margin: 0;
  background-color: #0f5257;
}

.container {
  width: 85%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
  margin: auto;
}
h1 {
  font-size: 1rem;

}
h2 {
  font-size: 0.9rem;
  margin: 10% 0;
  color: #fff;
}
.btn-color {
  padding: 3% 3%;
  border: none;
  border-radius: 5px;
  color: #0f5257;
  font-size: 1rem;
  cursor: pointer;
}

@media screen and (min-width: 992px) {
  /* For Large Laptops */
  .container {
    width: 100vw;
    margin: auto;
  }
  h1 {
    font-size: 2.5rem;
  }
  h2 {
    font-size: 1.8rem;
  }
  .btn-color {
    padding: 2% 2%;
    margin: auto;
    font-size: 1.7rem;
    font-weight: bold;
  }
}
Enter fullscreen mode Exit fullscreen mode

Here is what it will look like on a mobile screen.

Image description

Here is what it will look like on a larger screen.

Image description

You will animate the h1 tag using the CSS animation property. In your CSS give the h1 selector the property of animation and give it a name value of ‘hexcolors’ it will last for 5s and it should be infinite alternate. It alternates the colors.

...
h1 {
  font-size: 1rem;
  animation: hexcolors 5s infinite alternate;
}
...
Enter fullscreen mode Exit fullscreen mode

@keyframes add the name-value ‘hexcolors’, we will start animating the text colors at 0%. At 0% it should have a color #fe5e41, at 20% it should have a color of #646e68, at 40% it should have a color of #d8f1a0, at 60% it should have a color of #0075f2, at 80% it should have a color of #c7a27c, at 100% it should have a color of #a23b72.

...
@keyframes hexcolors {
  0% {
    color: #fe5e41;
  }
  20% {
    color: #646e68;
  }
  40% {
    color: #d8f1a0;
  }
  60% {
    color: #0075f2;
  }
  80% {
    color: #c7a27c;
  }
  100% {
    color: #a23b72;
  }
}
...
Enter fullscreen mode Exit fullscreen mode

The color of the h1 text keeps changing as seen below

Image description

Javascript Structure:

For the javascript part of the project,

  • create a folder called js and create an index.js file in it.
  • Go to your HTML code and link it to your js as seen below.
<script src="./js/index.js"></script>
Enter fullscreen mode Exit fullscreen mode
  • In your javascript file create a function called handleSubmit and create an array called hexNumbers, input all the hex numbers into it.
  • Hexadecimal color code start from 0 to 9 and from A to F.
function handleSubmit() {
  let hexNumbers = [
    "0",
    "1",
    "2",
    "3",
    "4",
    "5",
    "6",
    "7",
    "8",
    "9",
    "A",
    "B",
    "C",
    "D",
    "E",
    "F",
  ];
}

Enter fullscreen mode Exit fullscreen mode
  • Create a variable called hexColorCode and assign an empty string to it. This is where all the hex code you generate goes into.
  • Create a for loop that runs six times, starting from 0 to 5. This loop will generate the hex code for you.
  • Create a variable that generates a random index, this will help in picking a random hex number.
  • You will use the built-in math function to enable you to multiply your hex number array using the math.random function. This will return a decimal number, to change the decimal number to a whole number you will use the math.floor function in the codebase.
  • Next you will concatenate the hex numbers and the random index variable in the hexColorCode you created earlier on.
...
let hexColorCode = "";
  for (var i = 0; i < 6; i++) {
    let randomIndex = Math.floor(Math.random() * hexNumbers.length);
    hexColorCode += hexNumbers[randomIndex];
  }
...
Enter fullscreen mode Exit fullscreen mode
  • Get the id of the span tag using document.getElementById. This will change the display the hexadecimal color code on the screen. Also get the body tag using document.getElementByTagName, this will the background color of the body on click of the button.
...
  document.getElementById("colorCode").innerHTML = hexColorCode;
  document.getElementsByTagName("body")[0].style.background =
    "#" + hexColorCode;
Enter fullscreen mode Exit fullscreen mode

Here is the code base in CodePen:

Conclusion:

Bravo!!! You have learnt how to use two built-in math functions ( random and floor), just by building this project. You have also learned how to use the for loop. It's time to practice what you have learned. You can use this knowledge in building different awesome projects. A lot of websites change their background color randomly and so this knowledge will definitely not go to waste.

Top comments (0)