Random Joke Generator for the beginner (and that's no joke!)
Tags: beginners, html, css, javascript
Published: 2020-10-02 00:47:43

When I first started dabbling with JavaScript one of the first things I learned was the classic "Random Quote Generator". I remember thinking how cool it was to get something like that to work. I didn't care how simple it was or how many people had made one mine was so *cool*. 

It was my first time combining HTML, CSS and JavaScript together and seeing something happen in the browser. To me, **IT WAS AWESOME!**

So if you are a complete beginner this guide is going to be a great way to get your feet wet. Even if you aren't a beginner maybe you haven't done one in a while and would like a little refresher. 

Today we are going to build a Random Joke Generator. It's the same concept if you would rather use random quotes - this is yours to customize! 

In order to encourage you to customize the generator to your own style and imagination, this guide is going to be fairly plain when it comes to the CSS, doing the bare minimum for styling. 

Our final product is going to look like this:
{% codepen https://codepen.io/fitzwebdev/pen/qBZzpOe %}

First things first, lets get out project in order. In your project folder create three files - an index.html, style.css, and scripts.js. 

Let's get our HTML structure set up next. 

Start with the basic HTML skeleton:

```
<!DOCTYPE html>
<head>
<title></title>
</head>
<body>
</body>
</html>
```


Go ahead and fill in your `<title>` with "Random Jokes". This will display in your browser tab. Additionally let's add `<h1>Random Joke Generator</h1>` inside the `<body>`, followed by a `<div>` with `class="display"` that will contain a `<p>`. Add an `id="displayJoke"` to your `<p>`. This is where our jokes are going to be displayed when we add the JavaScript.


```
<!DOCTYPE html>
<head>
<title>Random Jokes</title>
</head>
<body>
   <h1>Random Joke Generator</h1>
   <div class="display">
   <p id="displayJoke">
     <!-- this is where jokes will display -->
   </p>
   </div>
</body>
</html>
```


Add another `<div>` with a `class="button-container"` and put a `<button>` in it with a `class="button"`. Give it text like this `<button class="button">Get Joke<button>` Before we forget, lets also link the CSS stylesheet in the `<head>` and link the JavaScript sheet by placing `<script src="scripts.js"></script>` directly before the closing `</body>`.


```
<!DOCTYPE html>
<head>
<link rel="sylesheet" href="style.css">
<title>Random Jokes</title>
</head>
<body>
   <h1>Random Joke Generator</h1>
   <div class="display">
   <p id="displayJoke">
     <!-- this is where jokes will display -->
   </p>
   </div>

   <div class="button-container">
     <button class="button>Get Joke</button>
   </div>

   <script src="scripts.js"></script>
</body>
</html>
```

When all put together in your editor it looks like this:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/8zlx0svb6e05zgaklvsy.png "HTML Structure")

Moving forward, we are going to jump straight into the JavaScript. This is because I want you to style the end product to make it your own! Don't fret, I'll still cover CSS at the end of the guide if you want to use it to build yours from. Without further ado, open up the scripts.js file. 

Lets grab the button using `querySelector()`. 

```
const onClick = document.querySelector("button");
```
Next, we need to make the actual array that contains all the jokes! Feel free to use the one's provided in this guide or completely make it your own and snag jokes you'd prefer to use instead! Write the array as follows:

```
const jokes = [
    "What rock group has four men that don't sing? Mount Rushmore.",
    "When I was a kid, my mother told me I could be anyone I wanted to be. Turns out, identity theft is a crime.",
    "What do sprinters eat before a race? Nothing, they fast!",
    "What concert costs just 45 cents? 50 Cent featuring Nickelback!",
    "What do you call a mac 'n' cheese that gets all up in your face? Too close for comfort food!",
    "Why couldn't the bicycle stand up by itself? It was two tired!",
    "Did you hear about the restaurant on the moon? Great food, no atmosphere!",
    "How many apples grow on a tree? All of them!",
    "Did you hear the rumor about butter? Well, I'm not going to spread it!",
    "I like telling Dad jokes. Sometimes he laughs!",
    "To whoever stole my copy of Microsoft Office, I will find you. You have my Word!"
]
```

When making the array, be sure to use square brackets `[ ]`to place the jokes in and separate each joke with a comma. 

Finally, it's time for the function that makes this whole things work!

Let's make our custom function and call it getJoke.

```
function getJoke() {

}
```

We are going to use some math in the function to randomly select a joke from our array of jokes - well JavaScrpt will use the math - we're just gonna type some math. Each joke in our array is an index starting at zero. The number of indexes we have is determined by the length of our array (**READ**: this is the number of jokes we have in the jokes array). 

We need to generate a random number between zero and the length of our jokes array. We are going to start with `Math.floor()`. This will take a parameter and round it down to the nearest integer. An example is `Math.floor(7.9)` will give you 7. So, if we give it `Math.random()` (which generates random decimal between zero and one), we will have the first part of our math to generate a random number between zero and the length of our array complete. So let's write it out:

```
let randomNumber = Math.floor(math.random();
```

This is only half of the equation. This will always return zero because `Math.random()` will always return a decimal between zero and one. With `Math.floor()` it will always be rounded down to zero.

Remember, we need random whole numbers in order to grab jokes from our array. We will achieve this by taking our `Math.random()` number and multiplying it by a whole number. 

As an example, if we multiply `Math.floor(Math.random() * 10)` for example it will always give us a number between 0 and 9. So how are we going to get it to always be a random number between zero and the number of jokes in our array? We are going to multiply `Math.random()` by our array length using `jokes.length`. So now we will have:

```
let randomNumber = Math.floor(Math.random() * (jokes.length));
```
The math is done! We will now generate a random whole number between zero and the length of our jokes array. 

Next we're going to take that random number and pull a random joke from our array and put it in our index.html file so we can display it for the users to see. We are going to accomplish this using the `id="displayJoke"` that we assigned to our `<p>`.

So let's grab that `id` to pass our joke string into. 

```
document.getElementById('displayJoke')
```

Now use `.innerHTML` to take a retrieved joke and add it to the HTML element. 

```
document.getElementById('displayJoke').innerHTML = jokes[randcomNumber];
```

So now we have a full function that looks like this:

```
function getJoke() {
     let randomNumber = Math.floor(Math.random() * (jokes.length));
     document.getElementById('displayJoke').innerHTML = jokes[randomNumber];
}
```

Almost done! Now we need to use `.addEventListener()` to call our function when the user clicks on the Get Joke button.

```
onClick.addEventListener("click", getJoke);
```

**ACTION**: Please check your file - right now your scripts.js file should look like this:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/amtn4tv4832c4tc5qfb9.png "JavaScript Setup")

As of right now we haven't touched our style.css sheet. This is where I encourage you to make this project your own. Style it to your heart's desire and link it in the comments below. You can now **WOW** your friends and family with awesome jokes. 

If you need a base to start with, check out the quick styling below:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/h71l8idbibr036j7sc0j.png "CSS Setup")

Here we are simply resetting the browser margin and paddings and establishing border-box. We center up the `<h1>` and `<p>` and style the text a bit. We'll take our `display` class and keep it from allowing the `<p>` to push all the way to the edges of the screen. We will center our button using the `button-container` class and then make the button look pretty with `button` and `button:hover` classes. 

Please, I encourage you to make this your own and see just how far you can push this joke generator. Again, feel free to link the results in the comments!