16.1 Random Message Generator

16.1 Random Message Generator

🎯 Learning Goals

  • Understand how to generate a random number within a range in JavaScript
  • Use the random number to select an element from an array
  • Output a random message to the user
 

📗 Technical Vocabulary

 
  • Array
  • Random
  • Index
 
notion image

Introduction to Random Message Generator!

Random Message Generators are fun and user-interactive elements that you can include on your website. They make your website more engaging and can be designed in a myriad of ways to suit your theme or purpose. In this lesson, we'll learn how to create a random message generator using JavaScript arrays and the built-in Math.random() method.

Step 1: Create a new CodeSandbox project

Head to codesandbox.io and create a new project using the JavaScript template. This gives you three files to start: index.html, index.mjs, and styles.css.

Step 2: Create an Array

 
The first element we'll need for our random message generator is an array to hold our potential messages. Your array can hold as many or as few messages as you like!
Write an array of messages in your JavaScript file. Reference the example below:
const messages = ["KWK scholars are awesome!", "We did that!!!!", "You're doing great!", "We did a phenomenal job learning how to code!!!!"];

Step 3: Write a Function to Display a Random Message

Our goal is to create a function that randomly displays one message from our messages array. To make that possible, we’ll need to generate a random number that will correspond to one of the messages in our array. Here's how we might generate a random number:
const randomIndex = Math.floor(Math.random() * messages.length);
  • Here, Math.random() generates a random decimal number between 0 and 1.
  • We multiply it by the length of our array to get a number within the range of our array indices.
  • However, since Math.random() can return 0 but never returns 1 and array indices must be whole numbers, we use Math.floor() to round down to the nearest whole number.
 
Now, we need to use our random number generator within a function. Here’s an example of how that function could look:
function displayRandomMessage() { const randomIndex = Math.floor(Math.random() * messages.length); const randomMessage = messages[randomIndex]; console.log (randomMessage); }
Right now, one random message from our function should print to your console.log when the function is called. After creating a displayRandomMessage function, call your function. Does a message from your array print to the console log? Does the message change if you refresh the console?

Step 4: Integrating HTML

Our nexts step is to build out the HTML of our site. Right now, the random message only prints to the console, and we want users to be able to see a random message when they click a button.
 
Let’s create a button in our HTML file:
<button id="random-message-button">Generate Random Message</button>
 
Now, we need to go back to our JavaScript file to update our function. Let’s create an alert in our function that will display a message when the button is clicked. We’ll also need an event listener (.addEventListener) to listen for when the button is clicked to trigger the function.
 
In our JavaScript file:
const messages = ["KWK scholars are awesome!", "We did that!!!!", "You're doing great!", "We did a phenomenal job learning how to code!!!!"]; document.getElementById('random-message-button').addEventListener('click', displayRandomMessage); function displayRandomMessage() { const randomIndex = Math.floor(Math.random() * messages.length); const randomMessage = messages[randomIndex]; alert(randomMessage); }
In this example, we're using addEventListener to call our displayRandomMessage function whenever the button is clicked. Each time it's called, it generates a new random index, selects the corresponding message, and then displays that message.
💡
The alert() function in the code above in JavaScript is a method that displays a popup message to the user with a specified string of text. It's often used for simple user notifications, as it is a pop-up that requires the user to dismiss the message before they can interact further with the web page. You might have encountered alerts that have popped up have asked if you are sure you want to close the page before leaving!

Step 5: Adding a Paragraph Element to Output Text

Hooray! Our random message generator is working great 🥳. But what if we wanted our random message to appear as text on our website instead of as an alert?
In that case, we will need to create an HTML element where the message will be displayed, and then update that element's text content with the random message when the button is clicked. Add a paragraph (<p>) under your button in the HTML file that will hold the random message:
<p id="random-message-display"></p
Next, we need to go back to our JavaScript file. We’ll need to make a variable for our "random-message-display" text element, and we’ll need to update our function to display the text content of a random message when the button is clicked. Try updating your function! Open the toggle below for some example code:
JavaScript Code File
var randomMessageButton = document.querySelector('#random-message-button'); var randomMessageDisplay = document.querySelector('#random-message-display'); var messages = ["KWK scholars are awesome!", "We did that!!!!", "You're doing great!", "We did a phenomenal job learning how to code!!!!"]; document.getElementById('random-message-button').addEventListener('click', displayRandomMessage); function displayRandomMessage() { var randomIndex = Math.floor(Math.random() * messages.length); var randomMessage = messages[randomIndex]; randomMessageDisplay.textContent = randomMessage; };

Step 6: Styling with CSS

Now that we’ve got the functionality of our random message generator working as expected, you can go ahead and style the page however you wish! Untoggle the code in the green box below for one example of how you might begin to customize the look of your site!
Random Message Generator Exemplar
Click on this Sandbox if you’d like to see all the code in practice from this lesson!
Code
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>Random Message Generator</title> <link href="styles.css" rel="stylesheet" type="text/css" /> </head> <body> <!-- Go to the index.mjs file to see how to code the random message generator!! --> <h1>Random Message Generator</h1> <!-- Version 1: Alert --> <button id="button1">Version 1: Alert</button> <!-- Version 2: Text --> <button id="button2">Version 2: Text</button> <p id="textDisplay"></p> <script src="script.js"></script> </body> </html>
// Ingredients to create a Random Message Generator: // 1) Array (to hold messages) // 2) Random number generator (to select an index from our array) // [Ingredient 1] An example array of messages const messages = ["KWK scholars are awesome!", "We did that!!!!", "You're doing great!", "We did a phenomenal job learning how to code!!!!"]; // [Ingredient 2] Random number generator // Use Math.random() to generates a random decimal number between 0 and 1. // Multiply it by the length of our array to get a number within the range of our array indices. // Since array indices must be whole numbers, use Math.floor() to round down to the nearest whole number. const randomIndex = Math.floor(Math.random() * messages.length); // See the random index that gets generated in the console! console.log(randomIndex) // Now, we can display our messages in two ways: // Version 1: As a popup alert // Version 2: As text on our website // VERSION 1 ----------------------------------------------- // Let's make a function to show our random message! It does 3 things: // - Generates a new randomIndex // - Indexes the mesages array with our randomIndex // - Shows a popup message to users, using the alert() function function displayRandomMessage() { const randomIndex = Math.floor(Math.random() * messages.length); const randomMessage = messages[randomIndex]; alert(randomMessage); }; // Use addEventListener to call our displayRandomMessage function when the button is clicked. document.getElementById('button1').addEventListener('click', displayRandomMessage); // VERSION 2 ----------------------------------------------- // There are two important HTML elements here: the button, and the text element that will show the message. In this example, we are showing the message using a paragraph element <p>. // When we make variables for each element, we need to reference them by their id, as declared in the index.html file. // In this example, the <button> id is "button2," and the <p> id is "textDisplay." const button = document.querySelector('#button2'); const paragraph = document.querySelector('#textDisplay'); // Now let's make a function to show our random message! // This function does 3 things: // - Generates a new randomIndex // - Indexes the mesages array with our randomIndex // - Changes the <p> content to be the selected message function displayMessage() { const randomIndex = Math.floor(Math.random() * messages.length); const randomMessage = messages[randomIndex]; paragraph.textContent = randomMessage; }; // When the button is clicked, we want the displayMessage function to run. // Let's use addEventListener to listen for the button click! button.addEventListener('click', displayMessage);
html { height: 100%; width: 100%; } body { font-family: sans-serif; } button { padding: 12px; margin-right: 15px; font-size: 12pt; background-color: #f4d6ff; border: none; /* Add rounded corners */ border-radius: 8px; /* Change how the cursor looks when hovering over the button! */ cursor: pointer; } button:first-of-type { background-color: #ffddc2; }
 
📝
Click here for a Medium Challenge 🌶🌶
Build a small site that generates random jokes when a button is clicked. And then!!!: what’s a joke without a punchline? Have another button that shows the punchline of the joke.