Generate Random Images Using Vanilla JavaScript

Find Saas Video Reviews — it's free
Saas Video Reviews
Makeup
Personal Care

Generate Random Images Using Vanilla JavaScript

Table of Contents

  1. Introduction
  2. Displaying a Random Image in the Browser
  3. Implementing the Feature
  4. Setting up the Markup
  5. Selecting the Image Using JavaScript
  6. Generating a Random Number
  7. Storing the Random Index
  8. Checking for Duplicate Images
  9. Displaying a New Image on Refresh
  10. Alternative Approach: Displaying Images Without Page Refresh

Introduction

In this article, we will learn how to use JavaScript to display a random image in the browser. We will explore a feature where every time someone visits the page, a different image is selected at random. The selected image will never repeat, ensuring a fresh viewing experience. We will also discuss how to implement this feature using pure JavaScript, without the need for page refresh. Let's dive in!

Displaying a Random Image in the Browser

To display a random image in the browser, we need to follow a series of steps. In the following sections, we will outline each step, providing clear instructions and explanations along the way.

Implementing the Feature

Before we start coding, let's set up the basic structure of our HTML markup. This will include an image element with a unique ID and an empty src attribute. We will also create a button element that will be used to trigger the random image selection. Additionally, we will define some CSS styles to ensure the images are displayed consistently and centered on the page.

Setting up the Markup

To set up the markup, you will need an image element with an ID and an empty src attribute. It is recommended to define a width and height for the image, as well as set the object-fit property to cover for consistent display. To center the image on the page, set the CSS properties display to block and margin to auto. Similarly, create a button element that will be used to trigger the random image selection and apply the same CSS properties to center it on the page.

Selecting the Image Using JavaScript

To select a random image using JavaScript, we will first need to obtain the paths to the images and store them in an array. Each path will correspond to a specific image. We will then save a reference to this array. To select an image randomly, we will use an index that points to an element in the array. By setting the src of the image element to the value at the selected index, we can display the corresponding image on the page.

Generating a Random Number

To generate a random number between 0 and 3 (as we have four images in our array), we will use the Math.random() function. This function generates a random number between 0 and 1. To ensure that we get an integer value, we will wrap the Math.random() function with Math.floor(). Multiplying the result of Math.random() by the length of our array will give us an integer between 0 and 3. The use of Math.floor ensures the number is rounded down to the nearest integer.

Storing the Random Index

To prevent the same image from being displayed twice in a row, we will store the randomly generated index in the browser's local storage. After setting the src of the image element, we can use the localStorage.setItem() method to store the randomIndex value under a specific key, such as "index". This allows us to retrieve the stored value and compare it against the current randomly generated index before setting a new image.

Checking for Duplicate Images

To prevent the display of duplicate images, we will introduce a condition that checks whether the newly generated randomIndex matches the value stored in local storage under the "index" key. By retrieving the value using localStorage.getItem() and converting it back to a number, we can compare it with the randomIndex. If there is a match, we will run the random image selection function again until a unique image is chosen.

Displaying a New Image on Refresh

To ensure that a new image is displayed every time the page is refreshed, we need to call the randomImage() function on page load. This will set an initial image on the page. By incorporating the condition discussed previously, we can guarantee that the same image is not displayed consecutively.

Alternative Approach: Displaying Images Without Page Refresh

If you want to display images without refreshing the page, the logic remains the same. However, instead of using local storage, you can store the randomIndex value in a variable. Since the page is not being refreshed, the index will persist until a new image is selected. By incorporating the randomImage() function into the button click event, you can display a new image on demand without reloading the entire page.

Conclusion

In this article, we explored how to display a random image in the browser using JavaScript. We learned how to implement a feature that ensures a different image is selected each time the page is visited, without any repetitions. We also discussed an alternative approach that allows for image display without page refresh. By following the outlined steps, you can easily incorporate this feature into your own projects. Happy coding!

Highlights

  • Learn how to display a random image in the browser using JavaScript
  • Ensure a fresh viewing experience with a new image every time the page is visited
  • Implement the feature using pure JavaScript without relying on page refresh
  • Store the random index in local storage to prevent duplicate image display
  • Use an alternative approach to display images without refreshing the page

FAQ

Q: Can I use this method to display more than four images? A: Yes, you can easily adapt the code to handle a larger number of images. Simply update the array containing the paths to the images and adjust the range of the random number generation accordingly.

Q: Can I customize the CSS styles for the image and button elements? A: Absolutely! Feel free to modify the CSS styles to suit your design preferences. You can adjust the dimensions, alignment, and other visual aspects to fit your needs.

Q: What if I want to display a random image on a specific event, rather than page load? A: You can call the randomImage() function whenever you want to trigger the display of a new image. Simply bind it to the desired event, such as a button click or any other user action.

Q: Is there a limit to how many images I can display using this method? A: There is no specific limit to the number of images you can display. As long as you provide the paths to the images in the array, the code will work regardless of the array size.

Are you spending too much time on makeup and daily care?

Saas Video Reviews
1M+
Makeup
5M+
Personal care
800K+
WHY YOU SHOULD CHOOSE SaasVideoReviews

SaasVideoReviews has the world's largest selection of Saas Video Reviews to choose from, and each Saas Video Reviews has a large number of Saas Video Reviews, so you can choose Saas Video Reviews for Saas Video Reviews!

Browse More Content
Convert
Maker
Editor
Analyzer
Calculator
sample
Checker
Detector
Scrape
Summarize
Optimizer
Rewriter
Exporter
Extractor