Random Colour Generator

Project Description

Uses an array of hexadecimal values to randomly generate a background colour for the web page.

You can view a completed version of the project here.

Your project folder

In your portfolio/js folder is a folder named colours that contains all the files you need for this JavaScript project.

In VS Code, open the project’s index.html web page and ensure the hyperlinks and personal details have been correctly updated.

Adding the JavaScript code

Follow the steps below to add the JavaScript code to the index.html file.

  1. Scroll down the web page until you see an empty pair of opening <script> and closing </script> tags.
  2. Click inside the empty pair of tags and paste the JavaScript code below.
    const arrHex = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"];
    const btnColor = document.querySelector("#btn-color");
    const strColorDisplay = document.querySelector("#color-display");
    
    btnColor.addEventListener("click", function () {
       let strHexColor = "#";
       for (let i = 0; i < 6; i++) {
          strHexColor = strHexColor + arrHex[getRandomNumber()];
       }
       strColorDisplay.textContent = strHexColor;
       document.querySelector(".theme-js").style.backgroundColor = strHexColor;
    });
    
    // Generate random number in range 0 - 15
       function getRandomNumber() {
       return Math.floor(Math.random() * arrHex.length);
    }
  3. Save your index.html file.
  4. Display the file in a web browser and verify it works correctly.

Uploading your project to GitHub

Upload the colours folder as a sub-folder of the portfolio/js folder on your GitHub account.