HTML stands for HyperText Markup Language. It is the most widely used and popular language for web application development. Created by Berners-Lee in 1991, but first published in 1995. HTML has gone through multiple versions over the years. HTML 4 was a popular breakthrough version that was published in the year 1999. HTML 4 garnered a lot of attention and saw quick and widespread adoption all over the globe for web application development. HTML 5 is the current version of the programming language and was published in the year 2012.

In this HTML Games article, we focus on the practical aspect of HTML, along with CSS and JavaScript in real-world applications. Since we also work with CSS and JavaScript to develop the game, you can consider them a prerequisite for this article.

In this article, you will code along with us an HTML Game - QUIZ using the three main languages in web development, namely, HTML, CSS, and JavaScript. So without further ado, let’s get started!

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Project Directory

The Project Directory should look like the image attached below, in the end.

html-quiz

Fig: Project Directory

index.html

This file contains all the HTML codes that we need for this game. Later on, we add CSS and JavaScript to be able to interact with the game and also to make it look good.

<!DOCTYPE html>

<html lang="en">

  <head>

    <meta charset="UTF-8" />

    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <meta http-equiv="X-UA-Compatible" content="ie=edge" />

    <link href="styles.css" rel="stylesheet" />

    <title>HTML Game - Quiz</title>

  </head>

  <body>

    <div class="container">

      <div id="question-container" class="hide">

        <div id="question">Question</div>

        <div id="answer-buttons" class="btn-grid">

          <button class="btn">Answer 1</button>

          <button class="btn">Answer 2</button>

          <button class="btn">Answer 3</button>

          <button class="btn">Answer 4</button>

        </div>

      </div>

      <div class="controls">

        <button id="start-btn" class="start-btn btn">Start</button>

        <button id="next-btn" class="next-btn btn hide">Next</button>

      </div>

    </div>

    <script src="script.js"></script>

  </body>

</html>

  • This file contains the basic HTML boilerplate code.
  • Import CSS stylesheet inside the head tag.
  • The title of the game, as usual, is defined within the head tag.
  • The layout of the web page is within the body tag.
  • We are using div tags to be able to add styles and layouts to HTML elements.
  • Note that most elements have a class or an id to identify those elements when working with JavaScript and CSS.
  • Import the javascript file in the end, within the body tag.
Get skilled in HTML5 and CSS3 with the Full Stack Java Developer Master's Program. Click to check out the program details! 

script.js

This file includes the code that makes the game work. Let’s go through the code and understand what each snippet of the code is for.

const startButton = document.getElementById("start-btn");

const nextButton = document.getElementById("next-btn");

const questionContainerElement = document.getElementById("question-container");

const questionElement = document.getElementById("question");

const answerButtonsElement = document.getElementById("answer-buttons");

let shuffledQuestions, currentQuestionIndex;

startButton.addEventListener("click", startGame);

nextButton.addEventListener("click", () => {

  currentQuestionIndex++;

  setNextQuestion();

});

function startGame() {

  startButton.classList.add("hide");

  shuffledQuestions = questions.sort(() => Math.random() - 0.5);

  currentQuestionIndex = 0;

  questionContainerElement.classList.remove("hide");

  setNextQuestion();

}

function setNextQuestion() {

  resetState();

  showQuestion(shuffledQuestions[currentQuestionIndex]);

}

function showQuestion(question) {

  questionElement.innerText = question.question;

  question.answers.forEach((answer) => {

    const button = document.createElement("button");

    button.innerText = answer.text;

    button.classList.add("btn");

    if (answer.correct) {

      button.dataset.correct = answer.correct;

    }

    button.addEventListener("click", selectAnswer);

    answerButtonsElement.appendChild(button);

  });

}

function resetState() {

  clearStatusClass(document.body);

  nextButton.classList.add("hide");

  while (answerButtonsElement.firstChild) {

    answerButtonsElement.removeChild(answerButtonsElement.firstChild);

  }

}

function selectAnswer(e) {

  const selectedButton = e.target;

  const correct = selectedButton.dataset.correct;

  setStatusClass(document.body, correct);

  Array.from(answerButtonsElement.children).forEach((button) => {

    setStatusClass(button, button.dataset.correct);

  });

  if (shuffledQuestions.length > currentQuestionIndex + 1) {

    nextButton.classList.remove("hide");

  } else {

    startButton.innerText = "Restart";

    startButton.classList.remove("hide");

  }

}

function setStatusClass(element, correct) {

  clearStatusClass(element);

  if (correct) {

    element.classList.add("correct");

  } else {

    element.classList.add("wrong");

  }

}

function clearStatusClass(element) {

  element.classList.remove("correct");

  element.classList.remove("wrong");

}

const questions = [

  {

    question: "Which one of these is a JavaScript framework?",

    answers: [

      { text: "Python", correct: false },

      { text: "Django", correct: false },

      { text: "React", correct: true },

      { text: "Eclipse", correct: false },

    ],

  },

  {

    question: "Who is the prime minister of India?",

    answers: [

      { text: "Narendra Modi", correct: true },

      { text: "Rahul Gandhi", correct: false },

    ],

  },

  {

    question: "Which one of these is used for mobile app development?",

    answers: [

      { text: "Flask", correct: false },

      { text: "Flutter", correct: true }

    ],

  },

 

  {

    question: "What is 4 * 3?",

    answers: [

      { text: "6", correct: false },

      { text: "12", correct: true },

    ],

  },

];

  • We declare all the variables that we will be needing in the game and set a default value.
  • We then add event listeners to the buttons to make them functional.
  • We define a function ‘startGame()’ that is attached to the Start button in the game:
    • On pressing the button, questions appear on the screen with answer choices.
    • Every time the game is restarted, questions get shuffled.
  • We define a function ‘setNextQuestion()’ that performs the following operations:
    • Calls the ‘resetState()’ function.
    • Calls the ‘showQuestion()’ function with the shuffled question as to the parameter.
  • We define a function ‘showQuestion()’ that takes in a question as a parameter and displays it on-screen.
    • Creates the answer buttons depending on the number of choices for each question.
  • We define a function ‘resetState()’ that performs the following operations:
    • Calls ‘clearStatusClass()’ function. 
    • Hides the ‘Next’ button until the answer is selected for a particular question. 
  • We define a function ‘selectAnswer()’’ that takes in the click event as the parameter:
    • Sets the selected button that was clicked by the user.
    • If the user has reached the end of all the questions, the restart button is displayed.
    • Displays the relevant output according to the user’s choice.
  • We define a function ‘setStatusClass()’ that sets the status of the question, whether the answer is true or not according to the user’s choice.
  • We then define a function ‘clearStatusClass()’ that, as the name suggests, clears the status of the question.
    • We define the color of the shape.
    • Then, we define the cell dimensions.
    • Lastly, we define a list of questions and answers that we want to keep in this Quiz.

    styles.css

    This file contains the code that we use to stylize the elements of the HTML Quiz game. Let’s go through the stylesheet and understand all the styles applied to this project.

    *,

    *::before,

    *::after {

      box-sizing: border-box;

      font-family: Gotham Black;

    }

    :root {

      --hue-neutral: 200;

      --hue-wrong: 0;

      --hue-correct: 145;

    }

    body {

      --hue: var(--hue-neutral);

      padding: 0;

      margin: 0;

      display: flex;

      width: 100vw;

      height: 100vh;

      justify-content: center;

      align-items: center;

      background-color: hsl(var(--hue), 100%, 20%);

    }

    body.correct {

      --hue: var(--hue-correct);

    }

    body.wrong {

      --hue: var(--hue-wrong);

    }

    .container {

      width: 800px;

      max-width: 80%;

      background-color: white;

      border-radius: 5px;

      padding: 10px;

      box-shadow: 0 0 10px 2px;

    }

    .btn-grid {

      display: grid;

      grid-template-columns: repeat(2, auto);

      gap: 10px;

      margin: 20px 0;

    }

    .btn {

      --hue: var(--hue-neutral);

      border: 1px solid hsl(var(--hue), 100%, 30%);

      background-color: hsl(var(--hue), 100%, 50%);

      border-radius: 5px;

      padding: 5px 10px;

      color: white;

      outline: none;

      cursor: pointer;

    }

    .btn:hover {

      border-color: black;

    }

    .btn.correct {

      --hue: var(--hue-correct);

      color: black;

    }

    .btn.wrong {

      --hue: var(--hue-wrong);

    }

    .start-btn,

    .next-btn {

      font-size: 1.5rem;

      font-weight: bold;

      padding: 10px 20px;

      cursor: pointer;

    }

    .controls {

      display: flex;

      justify-content: center;

      align-items: center;

    }

    .hide {

      display: none;

    }

    • Define CSS styles for the body, which includes background, font styles, and a basic layout.
    • Define the style for the container and buttons.
    • Set hue colors that change according to the answer - right, wrong, or neutral.

    End Result

    The screenshot below is how the end result is expected to look.

    end-result

    We hope you had fun and learned the basics of HTML games and enjoyed going through this ‘Introduction to HTML Games’ article.

    Get Ahead of the Curve and Master HTML Today

    HTML is a programming language every programmer - aspiring or established needs to have in their arsenal. Having understood the fundamentals of the language, and gotten a practical walkthrough of how to develop an HTML game, your next step should be to enroll in a comprehensive program like our Full Stack Java Developer Masters’ Program. The program covers all the skills and practical training that you will need to become career-ready. To know more about the language, you can also check out our YouTube channel for video that provides a quick 101 or introduction to HTML and helps you learn how to develop a simple HTML game. 

    If you’re an aspiring mobile or web developer, HTML training is vital to broaden your skills and expand your career horizons. In case you have any questions for us regarding this article, do mention them in the comments section. We'll have our top experts address them for you at the earliest.

    Our Software Development Courses Duration And Fees

    Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

    Program NameDurationFees
    Caltech Coding Bootcamp

    Cohort Starts: 17 Jun, 2024

    6 Months$ 8,000
    Full Stack Developer - MERN Stack

    Cohort Starts: 24 Apr, 2024

    6 Months$ 1,449
    Automation Test Engineer

    Cohort Starts: 1 May, 2024

    11 Months$ 1,499
    Full Stack Java Developer

    Cohort Starts: 14 May, 2024

    6 Months$ 1,449