Random Image

Random Image Generator

Using HTML, CSS and JAVASCRIPT

In this particular blog we are going to create a random image generator using Html, Css and JavaScript. So everytime you refresh the page it’s going to load a bunch of images.

Using JavaScript we can add the number of rows and columns. We won’t be using any API key to load the images. In fact we are going to use a url to load the images. You can also specify a particular size of your choice.

We are going to insert these images into the DOM using JavaScript.

It’s a very simple project and wont need a lot of coding. Let’s see how

HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <link rel="stylesheet" href="style.css" />
    <title>Random Image</title>
  </head>
  <body>
    <h1>Random Image</h1>
    <h2>Refresh Me!</h2>
    <div class="container"></div>
    <script src="main.js"></script>
  </body>
</html>

Create a document type with a heading and a div tag. Do not forget to include the link for stylesheet in the <head> tag. Also include the JavaScript file before the closing </body> tag.



Css

@import url("https://fonts.googleapis.com/css2?family=Itim&display=swap");

* {
  box-sizing: border-box;
}

body {
  align-items: center;
  display: flex;
  flex-direction: column;
  font-family: "Itim", cursive;
  justify-content: center;
  min-height: 100vh;
  margin: 0;
}

.title {
  margin-top: 15px;
  text-align: center;
}

.container {
  align-items: center;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  max-width: 960px;
}

.container img {
  border-radius: 7px;
  object-fit: cover;
  height: 300px;
  margin: 10px;
  max-width: 100%;
  width: 290px;
}

Chose a font family that suits you the best. I went with “Itim”, cursive. You can implement your own ideas.


JavaScript

const container = document.querySelector(".container");
const unsplashURL = "https://source.unsplash.com/random/";
const rows = 5;

for (let i = 0; i < rows * 3; i++) {
  const img = document.createElement("img");
  img.src = `${unsplashURL}${getRandomSize()}`;
  container.appendChild(img);
}

function getRandomSize() {
  return `${getRandomNr()}x${getRandomNr()}`;
}

function getRandomNr() {
  return Math.floor(Math.random() * 5) + 300;
}

In main.js file get the hold of the container with document.querySelector along with the url. Using the foreach loop we are going to create an image element and get hold of the image source. You can get creative and use you own ideas and thoughts.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: