Fill a CSS grid with pictures

I have a collection of 100 images in the same size that I would like to arrange within a CSS grid.

The folder contains:

  • seperate-0.png
  • seperate-1.png
  • seperate-2.png
  • seperate-3.png
  • and so on...

The CSS code below shows the grid structure:

html,
body,
.grid-container {
    height: 100%;
    margin: 0;
}

.grid-container {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    grid-template-rows: repeat(7, 1fr);
    gap: 0px 0px;
    grid-template-areas: ". . . . . . ." 
                         ". . . . . . ."
                         ". . . . . . ."
                         ". . . . . . ."
                         ". . . . . . ."
                         ". . . . . . ."
                         ". . . . . . .";
}


/* For presentation only, no need to copy the code below */

.grid-container * {
    border: 1px solid red;
    position: relative;
}

.grid-container *:after {
    content: attr(class);
    position: absolute;
    top: 0;
    left: 0;
}

Below is the HTML structure:

<div class="grid-container">
  <div class="grid-container">img 1 here</div>
</div>

My question is, how can I dynamically populate this grid with the images from the folder? Would it be possible to generate divs based on the contents of the directory?

Answer №1

HTML

Created a new class called grid-container-parent

<div class="grid-container grid-container-parent">
</div>

JavaScript

var imagePath="./image/seperate-";
var numberOfImage=100;

var parentDIV = document.getElementsByClassName("grid-container-parent")[0];

for(var i=0;i<numberOfImage;i++){
    var tempDIV= document.createElement('div');
    tempDIV.setAttribute('class','grid-container');
    var innerHTML= `<img src='`+(imagePath+i)+`.png'></img>`
    tempDIV.innerHTML=innerHTML;
    parentDIV.appendChild(tempDIV);
}

Answer №2

To create a loop that generates and inserts img elements with the appropriate src, you can iterate from 1 to 100. Here is an example:

const container = document.querySelector('.image-container');
for (let i = 1; i <= 100; i++) {
  const img = document.createElement('img');
  img.src = `path-to-image/image-${i}.png`;
  container.append(img);
}

Make sure your HTML structure is similar to this:

<div class="image-container">
  <!-- Images will be inserted here -->
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with remounting in Nextjs 13

import { useRouter, useSearchParams, usePathname } from 'next/navigation'; export function useQueryParams() { const pathname = usePathname(); const router = useRouter(); const searchParams = useSearchParams()!; const updateQu ...

Can CSS actually generate accurate inches?

Can you accurately set the width of an element, like a div, in inches and expect it to maintain that width across different devices? Or will it simply scale at a ratio like 1in = 96px? Edit: Try using CSS to set an element's width in inches and then ...

When using `require('backbone')`, the returned object can vary depending on the file it is called in

backbone1.js var backbone1=require('backbone'); window.backbone=backbone1; backbone2.js console.log(window.backbone===require('backbone')); Why is the condition returning false. Shouldn't it return the same object everytime? E ...

Retrieving a particular value from an array received through Ajax in JavaScript

Ajax functionality $("#panchayat").change(function(){ var param = {'panchayat_id':$(this).val()}; alert (param['panchayat_id']); $.ajax({ type : 'POST', url : '<?php echo base_url();?>index.php/parent_taluk' ...

The function "onClick" within an external .js file is being referenced

Just starting to learn Javascript and experimenting with an onClick event for an image in an external .js file using the HTML tag. <script type="text/javascript" src="embed.js"> The code found in "embed.js" is as follows: var image1=new Image(); i ...

Tips for utilizing Plunker or JSFiddle to execute Angular2 code

I've been attempting to practice coding programs in Angular 2 using plnkr and jsfiddle. However, every time I try to run them, I encounter issues such as 404 errors or exceptions when I check the developer tools. Can anyone advise on the correct metho ...

html5-jquery checkbox change event not firing

I successfully implemented an on/off switch using the method outlined in for HTML5. The functionality of the switch itself is working perfectly - click on it to toggle between states and query the checked state of the input/checkbox. However, I am facing ...

Challenges with Media Queries post Integration of MUI Library in React

I have been scratching my head for the last few hours. I needed to utilize a react library to design my dog app for a project. Opting for the MUI library, it has been effective for the grid layout. However, the challenge arises when attempting to implement ...

Is there a way to use jQuery to toggle a child element when the parent is clicked?

There are three images displayed on a webpage, each accompanied by a list of three events. The desired functionality is that when a user clicks on an event, the corresponding information should be displayed below that event. Below is the HTML structure: & ...

Encountering issues with $.AJAX post in JavaScript, while successful in Advanced Rest Client

My JavaScript code is facing an issue when trying to communicate with the HttpPost service. Interestingly, I can access the same endpoint using the "Advanced Rest Client Application" for Chrome without any problems. However, when I execute my code in the C ...

What is the reason for the failure of the require("perf_hooks") function?

My understanding is that "perf_hooks" is a component of Node.js. However, when I run tests with npm test, it fails for me and shows the following error (some file names have been altered): Error: ENOENT: no such file or directory, open 'perf_hooks&apo ...

Encountering incorrect JSON formatting even though the content is accurate

I'm encountering an error while trying to fetch the JSON. It seems to be in the wrong format. Below is the JSON data: { "favorite_page_response": "<div class=\"col-md-12 col-lg-12\">\n <div class=\"cart\ ...

Having trouble with the JSFiddle dropdown button that is unresponsive to

I am currently in the process of developing a test drop-down menu. The open menu button functions correctly, however, the close button is unresponsive to clicking or hovering actions. Upon clicking the open menu button, it should make the other button visi ...

MongoDB subfield pagination technique

I am looking to retrieve specific data from a sub-field in a MongoDB collection and implement pagination for it. Thank you! { "_id": "616d274c655e0000ee005f32", "subscription": [ { "account_admin&q ...

The route param is throwing a "Cannot read property 'name' of undefined" error, indicating that the property

Currently, I am enrolled in an ExpressJS course on TUTS+ From the video tutorial, I have implemented the following code snippet (excerpt from video): var express = require('express'), app = express(); app.get('/name/:name', funct ...

Leveraging and utilizing TypeScript npm packages

My goal is to create shared code in TypeScript, package it as an npm package, and easily install it. I attempted to create an external library like this: export class Lib { constructor(){ } getData(){ console.log('getting data from l ...

Converting a child.jsp file into a modal or overlay using JavaScript: A step-by-step guide

Is it possible to call a child.jsp as a model using JavaScript? I previously accessed the child jsp using showmodaldialog and window.open() with JavaScript, but it opens in another window. I want the child jsp to appear in a modal or overlay view. Can some ...

Resizable table example: Columns cannot be resized in fixed-data-table

I've implemented a feature similar to the Facebook example found here: https://facebook.github.io/fixed-data-table/example-resize.html You can find my source code (using the "old" style with React.createClass) here: https://github.com/facebook/fixed- ...

Using AJAX in a WordPress template

I'm currently facing an issue with integrating my operational php/javascript/ajax application into my WordPress theme. This application is meant for my users and not within the admin panel. Steps I've taken: I have successfully included the Java ...

Angular 2 encountering troublesome JSON response with invalid characters

After fetching a JSON response from an external API, I noticed that one of the variable names starts with a # character, making it look like #text in the JSON structure. Unfortunately, Angular doesn't recognize this variable. Is there a way to remove ...