Skip to content

Instantly share code, notes, and snippets.

@acidtone
Last active October 19, 2021 11:41
Show Gist options
  • Save acidtone/fbfa8e15f7098f231e8cc52d0518ee2b to your computer and use it in GitHub Desktop.
Save acidtone/fbfa8e15f7098f231e8cc52d0518ee2b to your computer and use it in GitHub Desktop.
Spoilers: Array.forEach() - Create an array of Lorem Picsum images from an array of ids

Spoilers: Array.forEach() - Create a gallery of Lorem Picsum images from an array of image id's

A possible solution to this forEach() Activity.

<!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>Document</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. Create empty output variable that will contain the gallery images
let output = '';
// 2. Create a function `handleItem()` that accepts the array `item` (the Picsum image id) as a parameter
const handleImageId = function(imageId){
// 3. In this new function, take the Picsum image id and create a valid img element that's 300px x 300px
// <img src="https://picsum.photos/id/[imageId]/300/300" alt="Lorem Picsum Image">
output += `<img src="https://picsum.photos/id/${imageId}/300/300" alt="Lorem Picsum Image">`
}
// 4. Using Array.forEach(): loop through each Picsum image id, invoking handleItem() for each item.
picsumIds.forEach(handleImageId);
// 5. Using a method of your choice, output the image to `index.html` so that a gallery of all images is displayed on the page
const gallery = document.querySelector('.gallery');
gallery.innerHTML = output;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment