This post will give you a step-by-step guide on how to display random content on your website. That content can range from news headlines, images or videos.
There are a few potential benefits to displaying random content on a website:
- Keeps things fresh: If the same content is displayed all the time, users may become bored and less likely to visit the site. By showing a variety of content, the site can feel more dynamic and encourage users to come back.
- Increases engagement: If users see new content each time they visit the site, they may be more likely to spend more time on the site exploring the different content.
- Enhances SEO: Search engines like Google often rank sites higher if they see that the content is regularly updated.
- Increases user interest: If the random content is relevant and exciting to users, it can help keep them engaged and encourage them to return to the site.
Display Random Content with JavaScript
To display random content on your website with Javascript, you will need to use the Math.random() and Math.floor() functions. By combining these two methods, you can generate a random number whenever the website reloads, and you can use this number with conditional statements to display a particular content on your website.
Before diving in deeper, first, you need to understand the Math.floor() and Math.random() functions.
Math.random() and Math.floor() Javascript Methods
The Math.random() function is a built-in function in JavaScript that returns a random number between 0 (inclusive) and 1 (exclusive). That means that the function will return a floating-point number that is greater than or equal to 0, but less than 1.
Here is an example of how you might use the Math.random() function in JavaScript:
1 2 |
let randomNumber = Math.random(); console.log(randomNumber); // Outputs a random number between 0 and 1// In our case we got: // 0.09585104652199439 |
You can use the Math.random() function to generate a random number within a specific range by multiplying the result by the desired range, and then using the Math.floor() function to round the number down to the nearest integer. For example:
1 2 |
let randomNumber = Math.floor(Math.random() * 10); console.log(randomNumber); // Outputs a random integer between 0 and 9 |
You can also use the Math.random() function to generate a random number within a range that is not starting at 0 by adding the lower bound of the range to the result.
For example, if we wanted to generate random numbers between 1 and 5, we would use the formula below.
1 2 |
let randomNumber = Math.floor(Math.random() * 4) + 1; console.log(randomNumber); // Outputs a random integer between 1 and 4 |
Now that you have a good understanding of the Math.floor() and Math.random() functions, you can start working on your code.
Step 1: Setup your Text Editor
You will need to create two files for this particular post – the index.html file, where you will write the HTML code and the index.js file, where you will write your Javascript code. We won’t need any index.css file for this post as we won’t do much styling.
The image below shows you how we set up the VS Code text editor for this post.
Step 2: Write the HTML Code
For this post, we want the website to generate Random content of some of the latest published blogs at the top. Below is the HTML code that we will use.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
<!DOCTYPE html> <html> <head> <style> body { margin: 0; padding: 0; } div { width: 100%; height: 200px; display: flex; align-items: center; flex-direction: column; color: red; border: 2px solid red; } </style> </head> <body> <div id="content_1"> <h1>Headline News 1</h1> <h2>How to Use Canva Docs on a Mobile Phone — The Ultimate Guide</h2> </div> <div id="content_2"> <h1>Headline News 2</h1> <h2>How to Connect Instagram to Canva in 12 Simple Steps</h2> </div> <div id="content_3"> <h1>Headline News 3</h1> <h2>5 Ways to Fix a Broken Dial Pad on Android</h2> </div> <div id="content_4"> <h1>Headline News 4</h1> <h2>Apply a Brand Kit to a Template in Canva — Super Easy!</h2> </div> <img src="image.png" alt="Website Screenshot" width="100%" height="auto" /> <script src="index.js"></script> </body> </html> |
Let’s have an in depth look at the code above.
First, we have four <div> tags that hold <h1> and <h2> tags which contain information about the titles of the published blogs. You will notice that every <div> tag has a unique id starting from “content-1” up to “content-4.”
These unique IDs will help you manipulate each element using Javascript and decide which you want to display. We also have an <img> tag at the bottom which displays a screenshot of our website below the headlines.
When you open this code on a browser, you should see something similar to the image below.
Currently, the website is displaying all the headlines. However, we want it to randomly display only one headline whenever a user visits or reloads the site. That is where the Javascript code comes into play.
Step 3: Write the Javascript Code
To manipulate how the HTML elements are displayed on our website, we will make use of the popular document.getElementById() Method in Javascript.
The getElementById() method is a method in JavaScript that is used to retrieve an element from an HTML document by its id attribute. It is a part of the Document object, which represents the entire HTML document.
Below is the Javascript code for this post.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
let randomNumber = Math.floor(Math.random() * 4) + 1; window.onload = function() { if (randomNumber == 1) { document.getElementById("content_1").style.display = ""; document.getElementById("content_2").style.display = "none"; document.getElementById("content_3").style.display = "none"; document.getElementById("content_4").style.display = "none"; } if (randomNumber == 2) { document.getElementById("content_1").style.display = "none"; document.getElementById("content_2").style.display = ""; document.getElementById("content_3").style.display = "none"; document.getElementById("content_4").style.display = "none"; } if (randomNumber == 3) { document.getElementById("content_1").style.display = "none"; document.getElementById("content_2").style.display = "none"; document.getElementById("content_3").style.display = ""; document.getElementById("content_4").style.display = "none"; } if (randomNumber == 4) { document.getElementById("content_1").style.display = "none"; document.getElementById("content_2").style.display = "none"; document.getElementById("content_3").style.display = "none"; document.getElementById("content_4").style.display = ""; } } |
When you open your HTML code on a browser, you should now see only one headline which will change whenever you reload the site.
Understanding the Code
- In the first line, we declared a variable called randomNumber and set its value to a Javascript formula – Math.floor(Math.random() * 4 + 1).
The expression Math.floor(Math.random() * 4 + 1) generates a random integer between 1 and 4 (inclusive).
Here’s how it works:
- Math.random() returns a random number between 0 and 1 (not including 1).
- Math.random() * 4 returns a random number between 0 and 4 (not including 4).
- Math.floor(Math.random() * 4) rounds down the number generated by Math.random() * 4 to the nearest integer. For example, if Math.random() * 4 returns 3.7, Math.floor(Math.random() * 4) will return 3.
- Finally, Math.floor(Math.random() * 4) + 1 adds 1 to the result, so the final expression returns a random integer between 1 and 4 (inclusive).
- The code then defines an anonymous function and assigns it to the window.onload event handler. This function will be executed when the web page finishes loading.
- The function contains four if statements, one for each possible value of the random number. Each if statement checks the value of randomNumber and displays the corresponding element if the value matches.
- If randomNumber is 1, the element with the ID “content_1” is displayed, and the other elements are hidden.
- If randomNumber is 2, the element with the ID “content_2” is displayed, and the other elements are hidden.
- If randomNumber is 3, the element with the ID “content_3” is displayed, and the other elements are hidden.
- If randomNumber is 4, the element with the ID “content_4” is displayed, and the other elements are hidden.
This code will display one of the four elements randomly on the webpage when it is loaded.
Note: It’s important to note that random content should be relevant and of high quality in order to be effective. If the content is not useful or interesting to users, it may have the opposite effect and drive them away.
Frequently Asked Questions about How to Display Random Content with JavaScript
How can I display a random element from an array on my webpage using JavaScript?
You can use the Math.random() function to generate a random number between 0 and the number of elements in the array. You can then use this random number to select a random element from the array and display it on your webpage.
How can I display a random image on my webpage using JavaScript?
You can use the Math.random() function to generate a random number between 0 and the number of images in your image array. You can then use this random number to select a random image from the array and display it on your webpage.