Skip to content

Instantly share code, notes, and snippets.

@acidtone
Last active February 15, 2022 13:18
Show Gist options
  • Save acidtone/c258994667d221be15ea794548d13b59 to your computer and use it in GitHub Desktop.
Save acidtone/c258994667d221be15ea794548d13b59 to your computer and use it in GitHub Desktop.
JS Activity: for loop - Create an array of Lorem Picsum images from an array of ids

JS Activity: for loop - Create a gallery of Lorem Picsum images from an array of image id's

In this activity, you will take a list of image IDs listed in picsum-list.js and create a gallery of images using the Lorem Picsum service.

Lorem Picsum is an image service that allows you to embed placeholder photos into your web pages. The images are pulled from open-source Unsplash images.

For example, the following HTML displays this puppy image

<img src="https://picsum.photos/id/237/300/300" alt="Lorem Picsum Image">

Lorem Picsum Image

Instructions

  1. Declare an empty string variable named output or similar.
  2. Create a for loop so that i iterates through each index of the array:
    • initialized at i = 0;
    • increments by one with each iteration;
    • stops after i equals Array.length - 1.
  3. Inside the for loop, use the output variable and the addition assignment operator (+=) (or another method of your choice) create an img list so that:
    • each image src is based on the image ID in the array:

      <img src="https://picsum.photos/id/[imageId]/300/300" alt="Lorem Picsum Image">
    • the image dimensions are 300px x 300px.

  4. Finally, after the for loop finishes, use Element.innerHTML to assign your output string to page element.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Picsum Image List</title>
<link rel="stylesheet" href="main.css">
<script src="picsum-list.js" defer></script>
</head>
<body>
<h1>Picsum Image List</h1>
<section class="gallery">
</section>
</body>
</html>
.gallery {
display: flex;
flex-wrap: wrap;
justify-content: center;
max-width: 1024px;
margin: auto;
}
.gallery > * {
margin: 1em;
}
const picsumIds = [
237,
433,
577,
582,
593,
659,
718,
783,
790,
837,
1024,
1025,
1074,
1084
];
// 1. Declare an empty string variable named `output` or similar.
// 2. Create a for loop that iterates through the above array.
// 3. Inside the for loop, build the output string using the addition assignment (+=) operator.
// 4. After the loop finishes, assign your output string to a paragraph element using `Element.innerHTML`.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment