Color Guessing Game using HTML , CSS and JavaScript

Introduction :

The Color Guessing Game is an interactive web application designed to test and enhance a user’s ability to recognize and guess colors. The game presents a series of color codes, and users must choose the correct color from a set of options. It is built using HTML, CSS, and JavaScript, and offers a simple, engaging way to learn and practice color recognition.

It is an engaging and interactive web application designed to challenge and enhance a user’s ability to recognize and guess colors accurately. This project, built using HTML, CSS, and JavaScript, provides a fun and educational experience by presenting users with a series of color codes displayed in hexadecimal format. The user’s task is to match these codes with the correct color from a set of given options.

This game leverages the inherent appeal of visual learning and the universal familiarity with colors to create an enjoyable and stimulating activity. It serves as an excellent tool for anyone looking to improve their understanding of color codes, which are commonly used in web design, graphic design, and various digital applications. By integrating a countdown timer and a scoring system, the game introduces an element of competition and urgency, making it both thrilling and educational.

The simplicity of the game’s premise—identifying the correct color from a set of options—belies the complexity of its implementation. The project showcases a well-structured approach to web development, highlighting the seamless integration of front-end technologies to deliver a smooth and responsive user experience. Each round of the game dynamically generates new questions, ensuring that the gameplay remains fresh and challenging.

From a developmental perspective, the Color Guessing Game exemplifies best practices in web development. It demonstrates the effective use of HTML for structuring content, CSS for styling and layout, and JavaScript for dynamic content manipulation and game logic. The codebase is modular and organized, making it easy to understand, maintain, and extend.

The educational value of this game is significant. It not only helps users familiarize themselves with hexadecimal color codes—a fundamental aspect of web design—but also enhances their ability to quickly distinguish between similar colors. This skill can be particularly valuable for designers, developers, and anyone involved in visual arts and digital media.

Overall, the Color Guessing Game is a delightful blend of education and entertainment. It exemplifies how simple concepts can be transformed into interactive and engaging web applications through thoughtful design and coding practices.

Explanation :

HTML Structure:

The HTML structure of the Color Guessing Game is designed to provide a clean and organized layout, ensuring that the game’s elements are easy to navigate and interact with. Here’s a breakdown of the key components:

  1. Title and Meta Tags:

    • The title of the webpage is “Color Guessing Game,” which will be displayed in the browser’s title bar or tab.
    • The project may include meta tags for responsive design and character set definitions (though not shown in the provided code).
  2. Main Containers:

    • display-container: This is the primary container that holds the game’s content, including the header, the question and option display area, and navigation buttons.
    • start-screen: This initial screen contains a start button, prompting the user to begin the game.
    • score-container: This container is shown at the end of the game to display the user’s score and includes a restart button to allow the user to play again.
  3. Game Elements:

    • Header: Contains the game title and a timer. The flex-space class ensures the elements are spaced evenly.
    • Question Container: The container div dynamically holds the questions and options.
    • Control Buttons: The next-button advances the game to the next question. The restart button in the score-container allows users to restart the game.
    • Score Display: Displays the user’s score at the end of the game.

The HTML layout is both functional and visually appealing, providing a user-friendly interface that supports the game’s logic.

CSS Styling:

The CSS is designed to provide a visually appealing and consistent user experience. Key aspects include:

  1. General Styles:

    • The * selector applies a universal box-sizing and font family, ensuring consistency across all elements.
    • The body style sets the background color and removes default margins, creating a uniform background.
  2. Container Styling:

    • The start-screen and score-container are styled to be full-screen overlays with centered content, using flexbox for alignment.
    • The display-container is positioned centrally with a white background, rounded corners, and a subtle box shadow, making it stand out against the background.
  3. Button and Option Styling:

    • Buttons are styled to be visually appealing and easy to interact with, featuring rounded corners and shadow effects.
    • The option-div buttons are large, making them easy to click, and use background images to provide visual feedback for correct and incorrect answers.
    • The hide class is used to toggle the visibility of elements dynamically.
  4. Responsive Design:

    • Flexbox is used extensively (flex-space, flex) to create responsive layouts that adjust to different screen sizes and orientations.

JavaScript Logic:

The JavaScript code is the core of the game, responsible for generating questions, handling user interactions, and updating the UI based on game events. Here’s a detailed breakdown:

  1. Variable Initialization:

    • DOM elements are selected and stored in variables for easy access.
    • Game state variables (questionCount, scoreCount, count, countdown) track the game’s progress and timing.
  2. Helper Functions:

    • generateRandomValue(array): Selects a random element from an array, used for generating random color codes.
    • colorGenerator(): Creates a random hexadecimal color code by concatenating randomly selected characters from the letters array.
    • populateQuiz(): Fills the quizArray with questions. Each question consists of a correct color and three additional options, all generated randomly.
  3. Core Functions:

    • displayNext(): Advances the game to the next question or shows the score at the end. It updates the question count, manages the timer, and toggles visibility of elements.
    • timerDisplay(): Initializes a countdown timer for each question, updating the timer display and moving to the next question if time runs out.
    • quizDisplay(questionCount): Shows the current question and hides the others. This function dynamically updates the UI to reflect the current state of the game.
    • quizCreator(): Generates the HTML structure for the quiz questions and options, ensuring each question has a unique set of options and the correct answer.
  4. Event Handling:

    • checker(userOption): Checks if the user’s selected option matches the correct answer, updates the score, and provides visual feedback by adding classes (correct, incorrect) to the selected option.
    • initial(): Initializes the game state, setting up the first question and starting the timer.
    • restart.addEventListener("click", ...): Resets the game state and starts a new game when the restart button is clicked.
    • startButton.addEventListener("click", ...): Starts the game when the start button is clicked, initializing the game state and populating the quiz array.
  5. Flow Control:

    • The game’s flow is managed through function calls and event listeners, ensuring a smooth transition between game states (starting the game, answering questions, showing the score, and restarting).



					<title>Color Guessing Game</title>

<div id="display-container">
  <div class="header flex-space">
    <div class="title">
      <p>Color Guessing Game</p><div class='code-block code-block-8' style='margin: 8px 0; clear: both;'> <script type="litespeed/javascript" data-src=""
     crossorigin="anonymous"></script> <ins class="adsbygoogle"
     style="display:block; text-align:center;"
     data-ad-slot="9706922910"></ins> <script type="litespeed/javascript">(adsbygoogle=window.adsbygoogle||[]).push({})</script></div>

    <div class="timer"></div>

  <div id="container">

  <div class="flex-space">
    <div class="number-of-count">
      <span class="number-of-questions"></span>
    <div id="next-button">Next</div>

<div class="start-screen">
  <button id="start-button">Start</button>

<div class="score-container hide">
  <div id="user-score"></div>
  <button id="restart">Restart</button>


CSS (style.css)

					* {
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
  color: #19084e;
body {
  margin: 0;
  background-color: #9873fe;
button {
  border: none;
  outline: none;
  cursor: pointer;
.score-container {
  position: absolute;
  top: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #9873fe;
#restart {
  position: absolute;
  font-size: 1.2em;
  padding: 1em 3em;
  border-radius: 2em;
  box-shadow: 0 1em 3em rgba(37, 22, 80, 0.3);
.flex-space {
  display: flex;
  justify-content: space-between;
  align-items: center;
.flex {
  display: flex;
#display-container {
  background-color: #ffffff;
  position: absolute;
  width: 90%;
  max-width: 37em;
  transform: translate(-50%, -50%);
  left: 50%;
  top: 50%;
  padding: 3em 2em;
  border-radius: 0.8em;
  box-shadow: 0 1em 3em rgba(37, 22, 80, 0.3);
.header {
  padding: 0.5em;
  border-bottom: 1px solid #c8c5d1;
.header .title,
.timer span {
  font-weight: 600;
.question-color {
  font-size: 1.5em;
  text-align: center;
#container {
  margin-bottom: 1em;
.button-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1em;
  place-items: center;
.option-div {
  width: 100%;
  height: 10em;
  padding: 1em;
  margin: 0.3em 0;
  text-align: left;
  border-radius: 0.5em;
.option-div:disabled {
  cursor: not-allowed;
.correct {
  background: url("correct.svg");
.incorrect {
  background: url("incorrect.svg");
.incorrect {
  background-repeat: no-repeat;
  background-size: 3em;
  background-position: center;
#next-button {
  font-size: 1.1em;
  background-color: #9873fe;
  color: #ffffff;
  padding: 0.4em 2em;
  border-radius: 0.3em;
.hide {
  display: none;
#restart {
  margin-top: 6em;

JavaScript (index.js)

					let timer = document.getElementsByClassName("timer")[0];
let quizContainer = document.getElementById("container");
let nextButton = document.getElementById("next-button");
let numOfQuestions = document.getElementsByClassName("number-of-questions")[0];
let displayContainer = document.getElementById("display-container");
let scoreContainer = document.querySelector(".score-container");
let restart = document.getElementById("restart");
let userScore = document.getElementById("user-score");
let startScreen = document.querySelector(".start-screen");
let startButton = document.getElementById("start-button");
let questionCount;
let scoreCount = 0;
let count = 10;
let countdown;
//For hex codes
let letters = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"];

//Questions and Options Array
let quizArray = [];

const generateRandomValue = (array) =&gt;
  array[Math.floor(Math.random() * array.length)];

//Generate Hex Codes
const colorGenerator = () =&gt; {
  newColor = "#";
  for (let i = 0; i  {
  let expectedLength = 4;
  while (optionsArray.length  {
  for (let i = 0; i  {
    //increment questionCOunt
    questionCount += 1;
    //If last question
    if (questionCount == quizArray.length) {
      //hide question container and display score

      //User score
      userScore.innerHTML =
        "Your score is " + scoreCount + " out of " + questionCount;
    } else {
      //displau questionCount
      numOfQuestions.innerHTML =
        questionCount + 1 + " of " + quizArray.length + " Question";

      //display quiz
      //count=11(so it start with 10)
      count = 10;
      //clearInterval for next question
      //display timer

const timerDisplay = () =&gt; {
  countdown = setInterval(() =&gt; {
    timer.innerHTML = `<span>Time Left: </span> ${count}s`;
    if (count == 0) {
  }, 1000);

//Display Quiz
const quizDisplay = (questionCount) =&gt; {
  let quizCards = document.querySelectorAll(".container-mid");
  //hide other cards
  quizCards.forEach((card) =&gt; {

  //display current question card

//Quiz Creation
function quizCreator() {
  //randomly sort questions
  quizArray.sort(() =&gt; Math.random() - 0.5);

  //Generate quiz
  for (let i of quizArray) {
    //Randomly sort options
    i.options.sort(() =&gt; Math.random() - 0.5);

    //Quiz card creation
    let div = document.createElement("div");
    div.classList.add("container-mid", "hide");

    //Question number
    numOfQuestions.innerHTML = 1 + " of " + quizArray.length + " Question";

    let questionDiv = document.createElement("p");
    questionDiv.innerHTML = `<div class="question-color">${i.correct}</div>`;
    div.innerHTML += `
    <div class="button-container">
    <button class="option-div" data-option="${i.options[0]}"></button>
    <button class="option-div" data-option="${i.options[1]}"></button>
    <button class="option-div" data-option="${i.options[2]}"></button>
    <button class="option-div" data-option="${i.options[3]}"></button>

function checker(userOption) {
  let userSolution = userOption.getAttribute("data-option");
  let question =
  let options = question.querySelectorAll(".option-div");
  //If users clicked answer === correct
  if (userSolution === quizArray[questionCount].correct) {
  } else {
    options.forEach((element) =&gt; {
      if (
        element.getAttribute("data-option") == quizArray[questionCount].correct
      ) {
  //clear interval
  //disable all options
  options.forEach((element) =&gt; {
    element.disabled = true;

function initial() {
  quizContainer.innerHTML = "";
  questionCount = 0;
  scoreCount = 0;
  count = 10;

//Restart game
restart.addEventListener("click", () =&gt; {
  quizArray = [];

//When user clicks on start button
startButton.addEventListener("click", () =&gt; {
  quizArray = [];