Enhancing Grid Items with Images through JavaScript

I need assistance with positioning a specific div at the center of a 3x3 grid. Currently, this div is appearing as the last item in the grid.

The div elements are being generated through an event listener that triggers a function containing a for loop.

function displayDino(){
for (var i = 0; i < dinoData.length; i++) {
  const dinoDiv = document.createElement('div');
  dinoDiv.className = 'grid-item';
  dinoDiv.innerHTML = `<h3>${dinoData[i]["species"]}<h3><img src="images/${(dinoData[i]["species"].toLowerCase())}.png"><p>${dinoData[i]["fact"]}</p>`;
  document.getElementById('grid').appendChild(dinoDiv);
}

}

Additionally, I have another function that appends a different div to the grid:

function displayHuman(){
  const humanDiv = document.createElement('div');
  humanDiv.className = 'grid-item';
  humanDiv.innerHTML = `<h3>${human.name()}<h3><img src="images/human.png">`;
  document.getElementById('grid').appendChild(humanDiv);
}

Is there a way to generate this grid while ensuring that a specific div is always centered within it?

Thank you in advance for any assistance provided!

Answer №1

To ensure the human entry is centered both horizontally and vertically in a 3x3 grid, simply wait until reaching index 5 before adding the human. Once added, remember this action and proceed to iterate through the array without interruption.

function displayElements(){
var humanAdded = false;
for (var i = 0; i < dinoData.length; i++) {
  const elemDiv = document.createElement('div');
  elemDiv .className = 'grid-item';
  if(humanAdded == false && i == 5){
    elemDiv .innerHTML = `<h3>${human.name()}<h3><img src="images/human.png">`;
    humanAdded = true;
    i--;
  }else{
    elemDiv .innerHTML = `<h3>${dinoData[i]["species"]}<h3><img src="images/${(dinoData[i]["species"].toLowerCase())}.png"><p>${dinoData[i]["fact"]}</p>`;
  }
  document.getElementById('grid').appendChild(elemDiv);
}
}

Answer №2

Here's a tip: If you know the specific location to place your individual data within a grid, simply utilize the grid-row and grid-column css properties for that particular grid-child. Disregard the other grid-children and focus on styling that specific child. This allows you to position multiple elements wherever you desire in this manner.

var dinoData = ["Plateosaurus","Abelisaurus","Barsboldia","Litosoraus","Platicore","Manticore","Trynasoraus","Sicocoreus"];
var human = { name: "MEEEEEEEE"};
function displayDino() {
  for (var i = 0; i < dinoData.length; i++) {
    const dinoDiv = document.createElement('div');
    dinoDiv.className = 'grid-item';
    dinoDiv.innerHTML = `<h3>${dinoData[i]}<h3>`;
    document.getElementById('grid').appendChild(dinoDiv);
  }
}

function displayHuman() {
  const humanDiv = document.createElement('div');
  humanDiv.className = 'grid-item human';
  humanDiv.innerHTML = `<h3>${human.name}`;
  document.getElementById('grid').appendChild(humanDiv);
}
displayDino();displayHuman();
#grid{
  display: grid;
  grid-template-columns: auto auto auto;
}
.grid-item{
  display: flex;
  padding: 50px;
  justify-content: center;
  align-items: center;
}
.human{
  grid-row: 2/3;
  grid-column: 2/3;
}
<div id="grid">

</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

What is the best way to retrieve the index of an object within an array?

https://i.sstatic.net/We8lJ.pngHow can I retrieve the index of an object's array? https://i.sstatic.net/hmDKx.png I am looking to access the index of the items array within the form object. https://i.sstatic.net/OxePH.png When adding a new item row ...

unexpected behavior in vue-router transition

Currently, I am in the process of working on my personal website. For the frontend, I have been using Vue.js along with vue-router. Everything was functioning smoothly until today, as evidenced here: (you will need to scroll down or use the arrow key down ...

jQuery function for loading twice

Hey there, I have a question about the two load functions. Can anyone assist me? $(document).ready(function() { $('#link').click(function () { $("#top_menu").load("menu.php"); $("#content").load("content.php"); retur ...

Manipulate only the elements inside the designated container

My CSS/bootstrap file is quite extensive and the styles are affecting more than just the elements I intended to target. While I want it to have a broad impact, the CSS changes are impacting the entire page. Renaming every element to [name].slider is not ...

Exploring how to browse and dynamically assign image sources with JavaScript/jQuery in an Asp.net mvc 4 framework

On my .cshtml page, I have an <img/> tag. <img id="ImageID" alt="" width="100%" height="100%" /> I want to dynamically set the src attribute by selecting the image file path using a file control. Although I attempted the following code in my ...

Is it possible to target the initial sibling of a parent element using a CSS selector?

Is there a way to target the <p> element using only the id "Standort" as a constant? Any suggestions on how to accomplish this? <section> <header> <h2 class="licht"><span id="Standort" class="-sitemap-select-item-select ...

Tips for horizontally aligning an item in a flexbox only when it wraps onto a new line

In my layout, I have a container that consists of text on the left and a button on the right. The challenge I'm facing is ensuring proper alignment when they are on the same line versus when the button wraps to a new line on smaller screens. Ideally, ...

Splitting For Loop Buttons into Separate Rows in a Table in Vue

My first table row uses a for loop to create 5 buttons with different values. I am looking for a way to separate these buttons so that the second button appears in the second <tr> and replaces button2, while the next one appears in the third <tr&g ...

Different ways to change the ID query in findIndex() function?

When searching for the index of a specific attribute in a key-value array, you can use the following method: var index = peoples.findIndex(function(person) { return person.attr1 == "john" } But what if I want to replace "john" with a variable, like tar ...

How to resolve the issue of undefined location in React and Next.js?

I'm attempting to send some text based on the hosted URL (where my build is deployed), but I keep encountering this error: ReferenceError: location is not defined Check out my code here. export const getStaticProps = async ({ preview = false, previ ...

Trouble encountered in PHP: Generating a file from POST data and initiating download prompt for the user not functioning as intended

On my webpage, users fill out forms and input fields, which are then sent to a PHP page via Ajax and $_POST. The PHP file successfully writes the output to a txt file. However, I'm facing an issue trying to prompt the user to download the file on the ...

Utilizing Mongoose's populate method for multiple layers of nested data

Currently, I am honing my MEAN-stack skills by working on a movie website project. One of the tasks at hand is retrieving a movie document from the database. Within this movie document lies a property called reviews, which is an array of ObjectId's re ...

Error in GatsbyJS: Unable to retrieve data from property 'childImageFluid' due to undefined value

Currently tackling a Gatsby website, but running into an issue: "TypeError: Cannot read property 'childImageFluid' of undefined" Here's the code snippet from my Project.js file: import React from "react" import PropTypes from &quo ...

Having trouble accessing the sidenav's home page

I am currently utilizing Angular Material Design to develop a website, but I am encountering an issue where I am unable to open the home section of the side bar. Can anyone provide me with a solution or suggestion to resolve this issue? https://stackblitz. ...

Obtaining the file size on the client side using JSF RichFaces file upload

I am currently using version 4.3.2 of rich fileupload in JSF richfaces. The issue I am facing is that the files first get uploaded to the server and then an error is thrown if the file size exceeds a certain limit. Even though I have set a size restriction ...

Only one component in Angular is utilizing the scss design

I have a component that generates multiple buttons next to each other, each with a specific style. Additionally, each button is randomly assigned a different color based on its class. The issue I am facing is that when I include this component in one of m ...

What is the most Angularesque approach to setting a character limit on a textarea input?

I'm currently developing a directive that enforces maxlength on a textarea field (for HTML version < 5) using AngularJS. I want to ensure that it is implemented in a proper AngularJS manner, but I am facing some challenges in getting it to work sea ...

After closing a window in GXT, the Element will be removed using RootPanel's get(String id) method

I am working on a GWT project with the GXT framework, and I have an embed tag in my project.html as shown below: <embed type="application/nptta" width=100% height=100% id="testId"></embed> There is a formPanel that will use RootPanel.get("tes ...

What is the method in JavaScript to display the information stored in a title attribute?

Can anyone help me with this code snippet I have? <i class="my-class" title="AB"> ::before </i> I need to extract and output the value of the title attribute, which is AB Example output should be: <span class="my-class">AB</spa ...

Identifying the state of the sidebar is key

I am looking to create a script in JavaScript that can detect whether a sidebar has the class "active" or not. The sidebar is controlled by Bootstrap's toggle button, which adds the "active" class when clicked. <button type="button" id="sidebarCol ...