Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to Generate a Random Password using JavaScript?
Next article icon

Random Image Generator using JavaScript

Last Updated : 26 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will learn how to generate random images in fixed intervals using only HTML, CSS, and JavaScript.

Approach: The pictures which are going to be generated randomly on the website should be stored in the form of an array, these pictures are then displayed to the user within a regular time interval.  We use the setInterval() function which is an in-built function of JavaScript to set a timer between the images to display and we will use the floor(Math.random()*pics.length) method to generate a random number between 0 and the length of the array that is assigned to the images to display randomly.

Below is the step-by-step implementation of the above approach.

Step 1: In your HTML page, create an empty section that will contain the randomly generated pictures.

index.html
<!DOCTYPE html> <html>  <head>     <style>         * {             margin: 0%;             padding: 0%;             box-sizing: border-box;             font-family: Arial, Helvetica, sans-serif;         }          body {             background: rgba(120, 16, 180, 0.767);             height: 100%;             background-position: center;             background-repeat: no-repeat;             background-size: cover;         }          .container {             margin: 1.5vh 20vw;             margin-top: 10vh;             text-align: center;             background: rgb(39, 188, 209);             background: linear-gradient(118deg,                 rgba(39, 188, 209, 0.9783263647255778) 0%,                 rgba(6, 14, 101, 1) 100%);             opacity: 0.9;             color: white;             padding: 10px 10vw;             border-radius: 20px;             min-height: 15vh;         }          h1 {             text-transform: uppercase;         }          section {             height: 50vh;             width: 100%;             margin-top: -50px;             background-position: center;             background-repeat: no-repeat;         }     </style>  </head>  <body>     <div class="container">         <br>         <h1>Geeks For Geeks Courses</h1><br>         <p>             With the idea of imparting programming              knowledge, Mr. Sandeep Jain, an IIT              Roorkee alumnus started a dream,             GeeksforGeeks. Whether programming              excites you or you feel stifled,              wondering how to prepare for interview             questions or how to ace data structures              and algorithms, GeeksforGeeks is a              one-stop solution.         </p>         <br><br><br>         <section></section>         <br>     </div> </body>  </html> 

Output:


Step 2: In JavaScript, create an array of image links. The images inside the array are to be generated randomly on the webpage. We will call the indexes of this array randomly using Math.random function to be displayed. 

Create a JavaScript variable to store a random value calculated by using the Math library i.e.  Math.floor(Math.random()*pics.length). It is going to generate a random number between 0 and the length of the pics array, this would be assigned to the images inside the pics array to display them randomly. 

setInterval() is an in-built function of JavaScript which is used to set a timer between the images to display. It has 2 parameters, the function that needs to be executed, and the time interval between each generation.

Now combine all the JS codes in your HTML code.

index.html
<!DOCTYPE html> <html lang="en">  <head>     <meta charset="UTF-8">     <meta name="viewport" content="width=device-width, initial-scale=1.0">     <title> Image Generator</title>     <style>         * {             margin: 0%;             padding: 0%;             box-sizing: border-box;              font-family: Arial, Helvetica, sans-serif;         }          body {             background: rgba(120, 16, 180, 0.767);             height: 100%;             background-position: center;             background-repeat: no-repeat;             background-size: cover;         }          .container {             margin: 1.5vh 20vw;             margin-top: 10vh;             text-align: center;             background: rgb(39, 188, 209);             background: linear-gradient(118deg,                     rgba(39, 188, 209, 0.9783263647255778) 0%,                     rgba(6, 14, 101, 1) 100%);             opacity: 0.9;             color: white;             padding: 10px 10vw;             border-radius: 20px;             min-height: 15vh;         }          h1 {             text-transform: uppercase;         }          section {             height: 50vh;             width: 100%;             margin-top: -50px;             background-position: center;             background-repeat: no-repeat;         }     </style> </head>  <body>     <div>         <br>         <h1>Geeks For Geeks Courses</h1><br>         <p>            With the idea of imparting programming knowledge,             Mr. Sandeep Jain, an IIT Roorkee alumnus started a dream,            GeeksforGeeks. Whether programming excites you or you             feel stifled, wondering how to prepare for interview            questions or how to ace data structures and algorithms,             GeeksforGeeks is a one-stop solution.         </p>          <br><br><br>         <section></section>         <br>     </div>     <script>         const pics = [             'url( "https://media.geeksforgeeks.org/wp-content/uploads/20200316135008/red7.png")',             'url( "https://media.geeksforgeeks.org/wp-content/uploads/20200316135014/yellow3.png")',             'url( "https://media.geeksforgeeks.org/img-practice/[email protected]")',             'url( "https://media.geeksforgeeks.org/img-practice/banner/dsa-self-paced-course-overview-image.png")',             'url( "https://media.geeksforgeeks.org/img-practice/banner/complete-interview-preparation-thumbnail.png")',             'url( "https://media.geeksforgeeks.org/img-practice/banner/Amazon-Test-Series-thumbnail.png")',             'url( "https://media.geeksforgeeks.org/img-practice/banner/dsa-self-paced-thumbnail.png")'         ];         const pic = document.querySelector('section');          function showImage() {             var a = Math.floor(Math.random() * pics.length);             var img = pics[a];             pic.style.backgroundImage = img;         }          setInterval(showImage, 1000);     </script> </body>  </html> 

Output:


Next Article
How to Generate a Random Password using JavaScript?
author
archita2k1
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-Projects

Similar Reads

  • Random String Generator using JavaScript
    JavaScript is a lightweight, cross-platform, interpreted scripting language. It is well-known for the development of web pages, many non-browser environments also use it. JavaScript can be used for Client-side developments as well as Server-side developments. In this article, we need to create a Ran
    7 min read
  • Random Quote Generator Using HTML, CSS and JavaScript
    A Random Quote Generator is capable of pulling quotes randomly from an API, a database, or simply from an array. We will be designing a Random Quote Generator from scratch using HTML, CSS, JavaScript, and type.fit API. The webpage displays a random quote from a collection and upon the click of a but
    8 min read
  • Generate Random Number in Given Range Using JavaScript
    Here are the different ways to generate random numbers in a given range using JavaScript 1. Using Math.random(): basic ApproachThis is the simplest way to generate a random number within a range using Math.random(). [GFGTABS] JavaScript let min = 10; let max = 20; let random = Math.floor(Math.random
    3 min read
  • How to Generate a Random Boolean using JavaScript?
    To generate a random boolean in JavaScript, use Math.random(), which returns a random number between 0 and 1. Approach: Using Math.random() functionCalculate Math.random() function.If it is less than 0.5, then true otherwise false.Example 1: This example implements the above approach. [GFGTABS] Java
    1 min read
  • How to Generate a Random Password using JavaScript?
    Creating a random password generator is an excellent beginner-friendly project that can be useful in real-world applications. Passwords are vital for securing accounts, and strong, randomized passwords enhance security significantly. What We're Going to CreateWe will create a Password Generator appl
    5 min read
  • Generate random alpha-numeric string in JavaScript
    In this article with the help of javascript we are generating the alpha-numeric string of specific length using javascript, here are some common method Approach 1: Creates a function that takes 2 arguments one is the length of the string that we want to generate and another is the characters that we
    2 min read
  • Generate a Random Birthday Wishes using JavaScript
    In this article, we are going to learn how to create a webpage that generates random Birthday wishes using HTML, CSS, and JavaScript. Approach: To generate a random birthday wish we will follow the below-given steps. HTML Code: In this section, we will create a basic structure of the HTML file i.e.
    2 min read
  • Design Random Color Generator using HTML CSS and JavaScript
    A Random Color Generator app is used to create random colors with a simple button click, displaying both HEX and RGB codes that users can copy. It's built using HTML, CSS, and JavaScript, making it a handy tool for designers or developers who need quick color ideas. The app can also include a Dark M
    3 min read
  • Color Pallete Generator using JavaScript
    Color Palette Generator App using HTML CSS and JavaScript is a web application that enables use­rs to effortlessly gene­rate random color palettes, vie­w the colors, and copy the color codes to the­ clipboard with just a single click. There is also a search bar that allows the user to check differen
    4 min read
  • How to Create an Image Element using JavaScript?
    We will dynamically create an <img> element in HTML using JavaScript. When a button is clicked, we'll generate the <img> element and append it to the document. Using createElement() methodCreate an empty img element using document.createElement() method.Then set its attributes like (src,
    1 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences