PROJECT - Random Color Generator

PROJECT - Random Color Generator

Applications that have a client side facing front end can allow developers to create user interfaces that can be used to interact with different parts of your application. The process of taking input data and using this information to dictate parameters in the code.

We can first start by creating a variable with an array of possible characters, this array will be used to generate a HEX color code to be used in our CSS.

// Initialize Random HEX Color Code
const hexColorCode = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f" ];

In order to manipulate the CSS we need to select the different elements that we want to change, we can use the window object to select the different Elements by passing in each of their IDs.

// Initialize All Required DOM Elements
const mainSection = document.getElementById("mainSection");
const pickColor = document.getElementById("pickColor");
const pickButton = document.getElementById("pickButton");
// const copyButton = document.getElementById("copyButton");

To construct our HEX value for our color we can use a for loop to cycle through the hexColorCode array randomizing the selections until 6 characters are selected.

// Initialize the Random HEX Color Picker
pickButton.addEventListener("click", () => {
  let hexColorName = "#";
  for (let i = 0; i < 6; i++) {
    hexColorName += hexColorCode[getRandomArray()];
  }
  pickColor.style.color = hexColorName;
  pickColor.textContent = hexColorName;
  mainSection.style.backgroundColor = hexColorName;
});

const getRandomArray = () => {
  return Math.floor(Math.random() * hexColorCode.length);
};

Pressing the button repeatedly will genereate new HEX color codes from the array, and than applying it to the elements on our page to change the CSS color.

FULL CODE

// Initialize Random HEX Color Code
const hexColorCode = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f" ];

// Initialize All Required DOM Elements
const mainSection = document.getElementById("mainSection");
const pickColor = document.getElementById("pickColor");
const pickButton = document.getElementById("pickButton");
// const copyButton = document.getElementById("copyButton");

// Initialize the Random HEX Color Picker
pickButton.addEventListener("click", () => {
  let hexColorName = "#";
  for (let i = 0; i < 6; i++) {
    hexColorName += hexColorCode[getRandomArray()];
  }
  pickColor.style.color = hexColorName;
  pickColor.textContent = hexColorName;
  mainSection.style.backgroundColor = hexColorName;
});

const getRandomArray = () => {
  return Math.floor(Math.random() * hexColorCode.length);
};