Creating a Lottery Number Generator with HTML, CSS, and JavaScript

December 19, 2022 Off By Zak Morris

Welcome to our tutorial on the new tools that we have released – the Lottery Number Generator!

The Lottery Number Generator is an HTML file that allows users to generate a set of random lottery numbers with a single click of a button. The HTML file includes a style.css file to provide some basic styling, as well as a JavaScript script to handle the generation of the numbers.

Let’s take a closer look at the code:

<html>
  <head>
    <link rel="stylesheet" type="text/css" href="style.css">

    <title>Lottery Number Generator</title>
  </head>
  <body>
    <h1>Lottery Number Generator</h1>
    <p>Here are your random lottery numbers:</p>
    <ul>
      <li id="number1"></li>
      <li id="number2"></li>
      <li id="number3"></li>
      <li id="number4"></li>
      <li id="number5"></li>
      <li id="number6"></li>
    </ul>

    <button id="generate-button">Generate Numbers</button>
<a href="disclaimer.html" class="disclaimer-link">Disclaimer | </a>
<a href="https://tutorial.rocks" class="disclaimer-link">Tutorial Rocks</a>



    <script>
      const generateButton = document.getElementById("generate-button");
      const numbers = document.querySelectorAll("li");

      generateButton.addEventListener("click", generateNumbers);

      function generateNumbers() {
        numbers.forEach((number, index) => {
          number.innerHTML = Math.floor(Math.random() * 49) + 1;
        });
      }
    </script>
  </body>
</html>

Click Here to access a working prototype:

The HTML file starts with a head element that includes a link to the style.css file and a title element for the page. The body element contains the main content of the page, including a heading, a paragraph, and an unordered list of li elements that will be used to display the generated numbers.

The page also includes a “Generate Numbers” button and two links – one for the disclaimer and one for the tutorial. The button and the links are styled using the style.css file.

The JavaScript code is included in a script element at the bottom of the page. The code first selects the “Generate Numbers” button and the li elements using the getElementById and querySelectorAll methods. It then adds a click event listener to the button, which will trigger the generateNumbers function when the button is clicked.

The generateNumbers function uses the forEach method to iterate over the li elements, and sets the innerHTML of each element to a random number between 1 and 49 using the Math.random and Math.floor functions.

This is how the Lottery Number Generator works – when the “Generate Numbers” button is clicked, the code generates a set of random numbers and displays them in the li elements.