Project Description
Uses an array of hexadecimal values to randomly generate a background colour for the web page.
Setting up the base web page
Your first task is to set up the base web page.
- In your javascript/projects folder, create a new sub-folder named colours.
- Download the following file to this new javascript/projects/colours folder. index.html
- Give it the filename index.html.
- Update the website logo, favicon, <title> tag and the <footer> with your own details.
This file contains all the necessary HTML and CSS for this project.
Adding the JavaScript code
At the bottom of your index.html web page, just before the closing </body> tag, add the following JavaScript code within a <script> tag.
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 number in range 0 - 15 function getRandomNumber() { return Math.floor(Math.random() * arrHex.length); }
Save your finished file and verify it works correctly.