JavaScript Lottery Number Generator

Denisa Marcisovska
4 min readMay 6, 2020

For the last fews weeks I have been doing different JavaScript projects to help increase my JavaScript skill set. I felt that creating a javascript lottery number generator was a good next project because I could build on top of what I have already learned. For this project, I would need to append my numbers onto elements, and I learned how to do that when I created the tip calculator and I was also already familiar with math.random().

A live example of the code: https://dmarcisovska.github.io/javascript-lottery-number-generator/

Github code: https://github.com/dmarcisovska/javascript-lottery-number-generator

Brainstorming Process

Steps:

  1. Generate 6 random numbers from 1–45
  2. Check for duplicates
  3. Store these number in an array
  4. Sort the array in ascending order
  5. Create an html element to hold each array value
  6. Append the array value to each element
  7. Delete circle elements before function starts

For the JavaScript lottery number generator I knew I wanted it to generate 6 random numbers from 1–45 and then store these 6 numbers in an array. I would have to use math.random for it. I would then have to create a function to check for duplicates and not add these duplicate numbers to the array. When winners are announced lottery numbers are shown in ascending order so my next step would be to arrange the array numbers from smallest to largest. I then would append these elements to my existing html.

HTML

To create the html I am using a bootstrap starter template. I created a button that upon clicking will fire up my javascript lottery number generator function. I then added a div with an id of lotto. This is where I will append my elements I create in the javascript lottery number generator function.

<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="shortcut icon" type="image/png" href="assets/denisa-dev-favicon.png">
<link href='https://fonts.googleapis.com/css?family=Lato:300' rel='stylesheet' type='text/css'>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" href="styles.css">
<title>Lottery Number Generator</title>
</head>
<body>
<div class="container align-middle">

<h1 class="mb-2 light text-center">Lottery Number Generator</h1>
<hr>
<p> Click the button to generate 6 random numbers between 1 and 45.</p>

<div class="row justify-content-center mt-4 mb-4">
<button type="button" class="btn btn-info btn-lg" onclick="myFunction()">Generate Lotto Numbers</button>
</div>

<div class="row justify-content-center" id="lotto">
</div>

</div>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<script src="scripts.js"></script>
</body>
</html>

CSS

The CSS file contains styling for the layout, font, circles, hr elements, and the background image.

body {background: url("assets/landscape-5055384_1920.jpg")  no-repeat fixed 0 0 / cover;
font-family: 'Lato', sans-serif;
color: white;
text-align: center;
}h1 {
color: white;
margin-top: 100px;
margin-bottom: 20px;
}
p {
font-size: 18px;
}
hr {
display: block;
height: 1px;
border: 0;
width: 50px;
border-top: 2px solid #ccc;
margin: 20px auto 25px auto;
}
.circle {
width: 120px;
height: 120px;
border-radius: 50%;
background: rgba(0,0,0,.3);
font-size: 24px;
color: white;
line-height: 118px;
text-align: center;
border: 2px solid white;
}

JavaScript

I first created an empty array. I then created a function that will keep iterating through until my array reaches 6 random values. If the value is a duplicate it will not add it into the array and continue until 6 different values are reached. In the next step, I sort the array into ascending order and stored those results into an array called sorted. I then used a foreach function. For each element of the array, I create a span element and add the circle class and m-3 classes to it. I then set the value of each circle element to the value of the array and I appended each element to my existing html.

After completing these steps, I realized if I clicked the function twice, my 6 existing lottery numbers remained, and 6 more were added in addition. If I did this 3 times, 6 more numbers would be added to the pile. To prevent this, I added an if statement at the top of my JavaScript lottery number generator function to check if an existing circle element exists and if so delete it. It is important to add this to the top of your function, and not at the bottom, otherwise it will delete all your circle elements upon creation.

function myFunction() {// check if circle element exists, and delete it if it does
// prevent duplicate lotto number circles from popping up
if (document.getElementsByClassName('circle').length) {
const removeElements = (elms) => elms.forEach(el => el.remove());
removeElements( document.querySelectorAll(".circle") );
}
let arr = [];
while(arr.length < 6){
let r = Math.floor(Math.random() * 45) + 1;
if(arr.indexOf(r) === -1) arr.push(r);
let add = true;
// looks for duplicate numbers
// if duplicate exists it does not add it to the array
for(let y = 0; y < 45; y++) {
if(arr[y] == arr) {
add = false;
}
}
}//sorts array by ascending order and adds it into new array
const sorted = [...arr].sort((a,b)=>a-b);
// for each element of array it adds it creates an element
// and adds the class circle to each each
// and then appends it to the lotto element
sorted.forEach(function (content) {
let lotto = document.getElementById("lotto");
let circle = document.createElement('span');
circle.setAttribute('class', 'circle m-3');
circle.textContent = content;
lotto.append(circle);
});
}

Originally published at https://denisa.dev on May 6, 2020.

--

--