Source: Geeks for Geeks
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 useMath.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!
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.